我有以下mysql表Test_Results
| ID | Test_ID | Device_OS| Status | Date |
| 1 | 1 | Android | passed | 2015/10 |
| 2 | 1 | Android | failed | 2015/10 |
| 3 | 15 | iOS | passed | 2015/11 |
| 4 | 20 | Android | passed | 2015/11 |
| 5 | 27 | Android | passed | 2015/11 |
| 6 | 10 | iOS | failed | 2015/12 |
| 7 | 5 | Android | passed | 2015/12 |
我需要按月计算每个操作系统和组的唯一Test_ID的数量。 我写了一个查询来计算唯一测试的一般数量:
SELECT Run_Date, COUNT(DISTINCT Test_ID) FROM Test_Results
GROUP BY MONTH(Run_Date)
ORDER BY Run_Date DESC;
但我无法弄清楚如何打破Deivce_OS。 所以结果会看起来像这样:
Run_Date COUNT Android iOS
12/10/2015 3650 3650 2500
11/5/2015 1909 1909 1900
10/1/2015 1667 1667 1325
谢谢!
答案 0 :(得分:1)
首先,你不应该按月分组,除非你真的,真的打算这样做。其次,你应该习惯只使用SELECT
中GROUP BY
中的表达式。
第三,我认为你只需要条件聚合,如下所示:
SELECT YEAR(Run_Date), MONTH(Run_Date), COUNT(DISTINCT Test_ID),
SUM(Device_OS = 'Android') as Android, SUM(Device_OS = 'iOS') as iOS
FROM Test_Results
GROUP BY YEAR(Run_Date), MONTH(RUn_Date)
ORDER BY YEAR(Run_Date) DESC, MONTH(RUn_Date) DESC;
编辑:
我注意到您希望每月为操作系统进行唯一测试。为此,请以条件方式使用COUNT(DISTINCT)
:
SELECT YEAR(Run_Date), MONTH(Run_Date), COUNT(DISTINCT Test_ID),
COUNT(DISTINCT CASE WHEN Device_OS = 'Android' THEN Test_ID END) as Android,
COUNT(DISTINCT CASE WHEN Device_OS = 'iOS' THEN Test_ID END) as iOS
FROM Test_Results
GROUP BY YEAR(Run_Date), MONTH(RUn_Date)
ORDER BY YEAR(Run_Date) DESC, MONTH(RUn_Date) DESC;