如何从简单的SQL查询中对结果进行排序

时间:2012-04-10 00:51:39

标签: sql count rows

我的SQL

SELECT nce.id, nce.send, count( * ) AS total
FROM `newsletter_email` nce
WHERE 1
GROUP BY nce.id, nce.send

产生结果:

id  send    total
4   0       6
4   1       1
5   0       2
6   1       7
7   1       4
8   0       2
8   1       4
9   1       1

但我希望结果是:

id  send    no_send     total
4   6       1           7
5   0       2           2
6   7       0           7
7   4       0           4
8   4       2           6
9   1       0           1

我尝试了几种方法,但没有给出预期的结果。你能帮忙吗?

1 个答案:

答案 0 :(得分:3)

假设发送的值为1表示发送,0表示no_send,则可以简单地对send的值求和:

SELECT nce.id, 
   sum(nce.send) as Send, 
   sum(1 - nce.send) as NO_send, 
   count(nce.send) as Total
FROM `newsletter_email` nce
GROUP BY nce.id

但是,一般模式是:

SELECT nce.id, 
   sum(case when nce.send = 1 then 1 end) as Send, 
   sum(case when nce.send = 0 then 1 end) as NO_send, 
   count(nce.send) as Total
FROM `newsletter_email` nce
GROUP BY nce.id