我得到了下表:
**stats**
id INT FK
day INT
value INT
我想创建一个 SQL 查询,在一条语句中对最后一天、上周和上个月的值列中的值求和。
到目前为止我得到了这个:
select sum(value) from stats as A where A.day > now() - 1
union
select sum(value) from stats as B where B.day > now() - 7
union
select sum(value) from stats as C where C.day > now() - 30
这只返回第一个总和(值),我期望返回 3 个值。
运行:select sum(value) from stats as A where A.day > now() - X ( Where x = 1/7/30)
在不同的查询中正常工作。
查询有什么问题?谢谢!
最佳答案
UNION
隐含不同。像这样使用 UNION ALL
:
SELECT 'last day' ItemType, sum(value) FROM stats as A WHERE A.day > now() - 1
UNION ALL
SELECT 'last week', SUM(value) FROM stats as B WHERE B.day > now() - 7
UNION ALL
SELECT 'last month', SUM(value) FROM stats as C WHERE C.day > now() - 30
请注意:我添加了一个新列ItemType
来指示总和值的类型是什么last day
,上周
或 上个月
关于sql - 在一个语句中对同一字段进行多次 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13269314/