-1

我的 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

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

4

1 回答 1

3

假设 Send 的 send 值为 1,no_send 的值为 0,您可以简单地将 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
于 2012-04-10T00:58:30.690 回答