我有一个表,其中记录了服务器的停机时间。
我在 sqlfiddle 创建了这个表的简化版本。请看这里sqlfiddle
表有每条记录
Reason Month Down_Time
A May 2
A May 5
B May 5
C July 15
A July 3
B June 6
A June 8
C June 2
如果没有匹配的记录,我需要编写一个查询来获取给月和原因的所有组合与 NULL
例如:如果我需要获取系统在 5 月、6 月和 7 月由于原因 A、B 的停机时间或 D.. 我期待的是..
Reason Month DOWNTIME
A May 7
A June 8
A July 3
B May 5
B June 6
B July NULL
D May NULL
D June NULL
D July NULL
由于我们在给定月份的记录中没有 D,它应该是 NULL
这是我的查询:
SELECT Reasons.reason, Months.Month,sum( a.Down_time ) AS downtime
FROM tabledown a
RIGHT JOIN (
SELECT 'A' AS reason
UNION ALL SELECT 'B' AS reason
UNION ALL SELECT 'D' AS reason
) Reasons
ON a.reason = Reasons.reason
RIGHT JOIN (
SELECT 'May' AS month
UNION ALL SELECT 'June' AS month
UNION ALL SELECT 'July' AS month
) Months
ON a.Month = Months.month
GROUP BY Reasons.reason,Months.month
ORDER BY Reasons.reason
为什么我没有得到预期的输出:(