需要MySql选择的指导

时间:2012-11-22 10:13:02

标签: mysql sql select

嗨,我有一张这样的桌子

Activity     Date
---------------------
0          2012-11-20
1          2012-11-20
1          2012-11-20
1          2012-11-21
1          2012-11-21
0          2012-11-22

我需要选择记录为

 Day-wise total   0's    1's    Date  
------------------------------------------
     3             1      2     2012-11-20
     2             0      2     2012-11-21
     1             1      0     2012-11-22

1 个答案:

答案 0 :(得分:4)

您需要的是GROUP BY dateCOUNT(Activity)以获得Day-wise总数和CASE表达式以旋转1和0的值。我在这里使用SUM,但它的行为类似于COUNT

SELECT
  COUNT(Activity) AS "Day-wise total",
  SUM(CASE WHEN Activity = 0 THEN 1 ELSE 0 END) AS "0's",
  SUM(CASE WHEN Activity = 1 THEN 1 ELSE 0 END) AS "1's",
  `Date` AS "Date"
FROM Table
GROUP BY `Date`;

SQL Fiddle Demo