我有这张桌子:
+----+-------+-------------------+
| ID | Value | Date |
+----+-------+-------------------+
| 1 | 8 | 12/10/2015 8:00am |
| 1 | 10 | 12/10/2015 8:30am |
| 1 | 5 | 12/10/2015 9:00am |
| 1 | 11 | 12/10/2015 9:30am |
| 2 | 8 | 12/10/2015 8:00am |
| 2 | 6 | 12/10/2015 8:30am |
| 2 | 8 | 12/10/2015 9:00am |
| 2 | 9 | 12/10/2015 9:30am |
+----+-------+-------------------+
etc.
现在我有一个这样的查询(为简洁起见而简化):
SELECT ID, MAX(Value), MIN(Date)
FROM Values
WHERE ID IN (1,2,3,8)
GROUP BY (DATEPART(MINUTE, Date) / 60), ID
ORDER BY ID, MIN(Date)
返回的内容如下:
+----+-------+-------------------+
| ID | Value | Date |
+----+-------+-------------------+
| 1 | 10 | 12/10/2015 8:00am |
| 1 | 11 | 12/10/2015 9:00am |
| 2 | 8 | 12/10/2015 8:00am |
| 2 | 9 | 12/10/2015 9:00am |
| 3 | 12 | 12/10/2015 8:00am |
| 3 | 6 | 12/10/2015 9:00am |
| 8 | 51 | 12/10/2015 8:00am |
| 8 | 58 | 12/10/2015 9:00am |
+----+-------+-------------------+
我需要计算值字段的总和,如果,比方说,ID是1,2或3 我期待这样的事情:
+------------+-------+-------------------+
| IDfield | Value | Date |
+------------+-------+-------------------+
| IDstring1 | 30 | 12/10/2015 8:00am |
| IDstring1 | 26 | 12/10/2015 9:00am |
| IDstring2 | 51 | 12/10/2015 8:00am |
| IDstring2 | 58 | 12/10/2015 9:00am |
+------------+-------+-------------------+
或者,甚至更好:
+--------+--------+-------------------+
| Value1 | Value2 | Date |
+--------+--------+-------------------+
| 30 | 51 | 12/10/2015 8:00am |
| 26 | 58 | 12/10/2015 9:00am |
+--------+--------+-------------------+
我需要求和的ID是静态的,所以我想我可以选择其中一种解决方案,但我想不出办法这样做。
我会尝试更好地解释预期结果:
Value1 应包含值字段的SUM,其中ID为IN(1,2,3),按小时分组,如我在查询中所做的那样 Value2 应该只包含ID字段,其中ID = 8
编辑:添加了源表示例,更正了当前查询(我忘记将聚合MAX()放入SELECT中的字段值
编辑#2:添加了更好的解释
答案 0 :(得分:2)
数据库:PostgreSql
查询:
select sum("Value") as Value1, date from "Values" where id in(1,2,3) group by date
Union ALL
select sum("Value") as Value1, date from "Values" where id=8 group by date
答案 1 :(得分:2)
我想我终于得到了你想要的东西:
DECLARE @tbl TABLE(ID INT, Value INT, Date DATETIME);
INSERT INTO @tbl VALUES
(1,10,'12/10/2015 8:00am')
,(1,11,'12/10/2015 9:00am')
,(2,8,'12/10/2015 8:00am')
,(2,9,'12/10/2015 9:00am')
,(3,12,'12/10/2015 8:00am')
,(3,6,'12/10/2015 9:00am')
,(8,51,'12/10/2015 8:00am')
,(8,58,'12/10/2015 9:00am');
WITH Values123 AS
(
SELECT SUM(Value) AS Sum123,Date
FROM @tbl
WHERE ID IN(1,2,3)
GROUP BY Date
)
SELECT Values123.Sum123
,(SELECT SUM(Value) FROM @tbl WHERE Date=Values123.Date AND ID=8)
,Values123.Date
FROM Values123
结果
Sum123 Sum8 Date
30 51 2015-10-12 08:00:00.000
26 58 2015-10-12 09:00:00.000