我认为这可能很简单,但我没有在SQL中练习,也不太了解语法。
基本上我有一张大表,其中包含我想要绘制的不同User Complaints
(由problem ID
表示)和Timestamps
。
个人陈述非常简单明了。例如:
SELECT DATE( datetimebegin ) AS Date, COUNT( * ) AS CntProb1
FROM `problems`
WHERE problemID = "1"
GROUP BY Date, problemID;
SELECT DATE( datetimebegin ) AS Date, COUNT( * ) AS CntProb2
FROM `problems`
WHERE problemID = "2"
GROUP BY Date, problemID;
每张表给出了一个非常简单的输出:
Date, CntProb1
2013-03-11,4
2013-03-14,1
2013-03-17,7
Date, CntProb2
2013-03-12,2
2013-03-13,1
2013-03-14,3
2013-03-17,1
我需要像这样结合的结果:
Date, CntProb1, CntProb2
2013-03-11,4,0
2013-03-12,0,2
2013-03-13,0,1
2013-03-14,1,3
2013-03-17,7,1
我想如果你知道正确的SQL语法,这是非常简单的......某种加入?!
非常感谢任何帮助!
答案 0 :(得分:2)
您不需要JOIN来获得结果,您应该能够通过在聚合函数中使用CASE表达式来获取结果:
SELECT
DATE(datetimebegin) AS Date,
sum(case when problemID = '1' then 1 else 0 end) AS CntProb1,
sum(case when problemID = '2' then 1 else 0 end) AS CntProb2
FROM `problems`
WHERE problemID in ('1', '2')
GROUP BY DATE(datetimebegin);
如果您想使用count()
代替sum()
,那么您可以使用:
SELECT
DATE(datetimebegin) AS Date,
count(case when problemID = '1' then problemID end) AS CntProb1,
count(case when problemID = '2' then problemID end) AS CntProb2
FROM `problems`
WHERE problemID in ('1', '2')
GROUP BY DATE(datetimebegin);
请参阅两个查询的SQL Fiddle with Demo。