连接两个 select 语句的结果
我有一个用作事务日志的表:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您确实想将多个查询的结果集添加到一个中,请看一下 UNION 语法:
http://dev.mysql.com/doc/refman/5.0/en/union.html
但是,在这种情况下,请查看GROUP BY
您可以按
日期、操作 因此,每个操作每天都会生成一条记录,并且
SUM()
能够为您提供数量。例如:
将导致:
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, withSUM()
being able to give you the quantity.For example:
Will result in:
如果您展示了您真正想要的输出,将会有所帮助。
从您的“添加时”和“删除时”我猜测您不想要一个联合,但也许是这样的:(
带有
按日期分组
如果您选择多个日期。)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:
(with a
group by date
if you are selecting multiple dates.)