以下是按价格点按小时对事务进行分组的查询:
SELECT hour(Stamp) AS hour, PointID AS pricepoint, count(1) AS counter
FROM Transactions
GROUP BY 1,2;
样本输出:
+------+------------+---------+
| hour | pricepoint | counter |
+------+------------+---------+
| 0 | 19 | 5 |
| 0 | 20 | 14 |
| 1 | 19 | 3 |
| 1 | 20 | 12 |
| 2 | 19 | 2 |
| 2 | 20 | 8 |
| 3 | 19 | 2 |
| 3 | 20 | 4 |
| 4 | 19 | 1 |
| 4 | 20 | 1 |
| 5 | 19 | 4 |
| 5 | 20 | 1 |
| 6 | 20 | 2 |
| 8 | 19 | 1 |
| 8 | 20 | 4 |
| 9 | 19 | 2 |
| 9 | 20 | 5 |
| 10 | 19 | 6 |
| 10 | 20 | 1 |
| 11 | 19 | 10 |
| 11 | 20 | 2 |
| 12 | 19 | 10 |
| 12 | 20 | 3 |
| 13 | 19 | 10 |
| 13 | 20 | 10 |
| 14 | 19 | 8 |
| 14 | 20 | 3 |
| 15 | 19 | 6 |
| 15 | 20 | 8 |
| 16 | 19 | 11 |
| 16 | 20 | 10 |
| 17 | 19 | 7 |
| 17 | 20 | 17 |
| 18 | 19 | 7 |
| 18 | 20 | 9 |
| 19 | 19 | 10 |
| 19 | 20 | 12 |
| 20 | 19 | 17 |
| 20 | 20 | 11 |
| 21 | 19 | 12 |
| 21 | 20 | 29 |
| 22 | 19 | 6 |
| 22 | 20 | 21 |
| 23 | 19 | 9 |
| 23 | 20 | 23 |
+------+------------+---------+
如您所见,有些时间没有事务(例如上午7点),而有些时间只有单个价格点的事务(例如上午6点,只有价格点20,但没有价格点19的事务)。
当没有事务时,我想用“0”显示结果集,而不是像现在这样不在那里。
尝试在那里使用左外连接。inhour表包含值0..23
SELECT H.hour, PointID AS Pricepoint, COALESCE(T.counter, 0) AS Count
FROM inHour H
LEFT OUTER JOIN
(
SELECT hour(Stamp) AS Hour, PointID, count(1) AS counter
FROM Transactions
GROUP BY 1,2
) T
ON T.Hour = H.hour;
这将生成以下输出(为简洁起见而截断):
| 5 | 19 | 4 |
| 5 | 20 | 1 |
| 6 | 20 | 2 |
| 7 | NULL | 0 |
| 8 | 19 | 1 |
| 8 | 20 | 4 |
事实上我想要的是:
| 5 | 19 | 4 |
| 5 | 20 | 1 |
| 6 | 19 | 0 |
| 6 | 20 | 2 |
| 7 | 19 | 0 |
| 7 | 20 | 0 |
| 8 | 19 | 1 |
| 8 | 20 | 4 |
在我想要的输出中,值“0”放在给定时间内没有事务的价格点旁边。
欢迎您的建议!谢谢。
最佳答案
SELECT h.Hour, p.Pricepoint, COUNT(t.*) AS Count
FROM inHour h,
(SELECT DISTINCT PointId AS Pricepoint FROM Transactions) p
LEFT OUTER JOIN Transactions t
ON h.Hour = hour(t.Stamp) AND p.Pricepoint = t.PointID
GROUP BY h.Hour, p.Pricepoint
ORDER BY h.Hour, p.Pricepoint
我现在没有时间试试这个,所以如果不行就告诉我,我会努力调整的。