我在MySQL
表中有以下数据:
+-------------------------------------+-----------------+
| DATE | SipResponseCode |
+-------------------------------------+-----------------+
| 20 Feb | 200 |
| 20 Feb | 500 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 487 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 500 |
| 20 Feb | 500 |
| 20 Feb | 487 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 500 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 200 |
| 20 Feb | 500 |
| 21 Feb | 200 |
| 21 Feb | 487 |
| 21 Feb | 200 |
| 21 Feb | 487 |
| 21 Feb | 487 |
| 21 Feb | 487 |
| 21 Feb | 487 |
| 21 Feb | 200 |
| 21 Feb | 200 |
| 21 Feb | 487 |
| 21 Feb | 487 |
| 21 Feb | 500 |
我想编写SQL查询,以便它可以计算每天的SipResponseCode数200
,487
,500
+-------------------------------------+------------+-----------+--------+
| DATE | 200 | 487 | 500 |
+-------------------------------------+------------+--------------------+
| 20 Feb | 14 | 2 | 5 |
| 21 Feb | 4 | 7 | 1 |
我已经累了但无法得到正确的结果。
答案 0 :(得分:1)
如果值200,487和500是您在编写查询时知道的常量值,则可以在select子句的case语句中使用它们。
比case语句更具可读性的东西是使用带有条件的SUM()函数,它基本上会计算满足该条件的行数。试试这个:
SELECT dateColumn,
SUM(SisResponseCode = 200) AS '200',
SUM(SisResponseCode = 487) AS '487',
SUM(SisResponseCode = 500) AS '500'
FROM myTable
GROUP BY dateColumn;
答案 1 :(得分:0)
以下查询将为您提供结果,而不是您想要的结果,但稍后可以通过您的语言(PHP,C#等)轻松解析它。
SELECT DATE, GROUP_CONCAT(CAST(TEST AS CHAR(10000) CHARACTER SET utf8) SEPARATOR ",") AS myCol
FROM
(
SELECT DATE, CONCAT(SipResponseCode, "^", COUNT(*)) AS TEST
FROM table1
GROUP BY DATE, SipResponseCode
) a
GROUP BY DATE
答案 2 :(得分:0)
标准答案大致如下:
SELECT date
, sipresponsecode
, COUNT(sipresponsecode) x
FROM my_table
GROUP
BY date
, sipresponsecode;