连接两个 select 语句的结果

发布于 2024-08-13 05:50:32 字数 472 浏览 6 评论 0原文

我有一个用作事务日志的表:

Date  Action  Qty
11-23  ADD     1
11-23  REMOVE  2
11-23  ADD     3

我想要一个查询来分别聚合给定日期的所有 ADD 和所有 REMOVE。

这些 select 语句中的每一个都工作正常,但它们无法连接:

select date, sum(qty) as Added from table where action='Add' and date='11-23'

natural join

select date, sum(qty) as Removed from table where action='Remove' and date='11-23'

我可以将每个 select 语句的结果存储到表中,然后连接它们吗?有没有办法同时避免这一切?

谢谢- 乔纳森

I have a table serving as a transaction log:

Date  Action  Qty
11-23  ADD     1
11-23  REMOVE  2
11-23  ADD     3

I would like a query to aggregate all of ADDs and all of the REMOVEs separately for a given date.

Each of these select statements work fine, but they cannot be joined:

select date, sum(qty) as Added from table where action='Add' and date='11-23'

natural join

select date, sum(qty) as Removed from table where action='Remove' and date='11-23'

Can I store the results of each select statement to a table and then join those? Is there a way to avoid this all together?

Thanks-
Jonathan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

此生挚爱伱 2024-08-20 05:50:32

如果您确实想将多个查询的结果集添加到一个中,请看一下 UNION 语法:

http://dev.mysql.com/doc/refman/5.0/en/union.html


但是,在这种情况下,请查看GROUP BY

您可以按日期、操作 因此,每个操作每天都会生成一条记录,并且 SUM() 能够为您提供数量。

例如:

select 
  date,
  action, 
  sum(qty) AS Quantity 
from 
  table 
group by
  date, action

将导致:

11-23 | ADD    | 10
11-23 | REMOVE |  5
11-24 | ADD    |  4
11-24 | REMOVE |  3

Take a look at UNION syntax, if you really want to add the result sets of multiple queries into one:

http://dev.mysql.com/doc/refman/5.0/en/union.html


However, in this case, take a look at GROUP BY

You could group on Date, Action therefore resulting in one record per day per action, with SUM() being able to give you the quantity.

For example:

select 
  date,
  action, 
  sum(qty) AS Quantity 
from 
  table 
group by
  date, action

Will result in:

11-23 | ADD    | 10
11-23 | REMOVE |  5
11-24 | ADD    |  4
11-24 | REMOVE |  3
感性不性感 2024-08-20 05:50:32

如果您展示了您真正想要的输出,将会有所帮助。
从您的“添加时”和“删除时”我猜测您想要一个联合,但也许是这样的:(

select
    date,
    sum(if(action='ADD',qty,0)) as Added,
    sum(if(action='REMOVE',qty,0)) as Removed
from `table`
where date='11-23';

带有按日期分组如果您选择多个日期。)

It would help if you showed what output you actually want.
From your "as Added" and "as Removed" I'm guessing that you don't want a union, but maybe something like this:

select
    date,
    sum(if(action='ADD',qty,0)) as Added,
    sum(if(action='REMOVE',qty,0)) as Removed
from `table`
where date='11-23';

(with a group by date if you are selecting multiple dates.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文