2012-04-10 46 views
-1

我的SQL如何排序从一个简单的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 

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

+0

请定义什么的“发送'和'no_send'列的意思。是否“发送”特定发送事件的索引?我在该列中只看到1和0,因此不清楚第一个结果如何映射到期望的结果。 – 2012-04-10 00:55:36

回答

3

假设发送有1对发送和0值no_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 
+0

感谢它正常工作 – Alexd2 2012-04-10 01:04:39