2011-05-31 97 views
1

如何獲得每個用戶名的是,否,其他字段的總值?從每個領域獲得總價值?

我喜歡加總字段。

SELECT Username, 
    SUM(CASE WHEN type = 'Yes' THEN 1 ELSE NULL END) as Yes, 
    SUM(CASE WHEN type = 'No' THEN 1 ELSE NULL END) as No, 
    SUM(CASE WHEN type = '' THEN 1 ELSE NULL END) as Other 
    //How to get total of Yes/No/Other 
    FROM table 
WHERE source = 'CompanyName' "; 

也是最高的總數在最高的順序。使用

回答

2

0,而不是NULL,添加缺少的group by和使用COUNT(*)得到總的各組並責令結果:

SELECT Username, 
    SUM(CASE WHEN type = 'Yes' THEN 1 ELSE 0 END) as Yes, 
    SUM(CASE WHEN type = 'No' THEN 1 ELSE 0 END) as No, 
    SUM(CASE WHEN type = '' THEN 1 ELSE 0 END) as Other, 
    COUNT(*) as TOTAL 
    FROM table 
WHERE source = 'CompanyName' 
group by Username 
order by TOTAL desc; 

這假定type只能是「是」,「否」要麼 ''。

+0

感謝您的建議。總數呢? – user622378 2011-05-31 12:48:47

+0

@ user622378:請參閱更新。 – 2011-05-31 12:49:14

+0

'count(*)'是有道理的,但如果在那裏有'type ='maybe''值,將不會返回相同的值。 – Keith 2011-05-31 12:52:02

1

使用子查詢來總結你的結果,並添加排序:

select yes, no, other, yes + no + other as Total 
from (

    SELECT Username, 
     SUM(CASE WHEN type = 'Yes' THEN 1 ELSE 0 END) as Yes, 
     SUM(CASE WHEN type = 'No' THEN 1 ELSE 0 END) as No, 
     SUM(CASE WHEN type = '' THEN 1 ELSE 0 END) as Other 
     FROM table 
    WHERE source = 'CompanyName' 
) 
order by (yes + no + other) desc 
+0

@Johan - 我可能讀過這個錯誤,但是他不想總得到總數並按它排序降? – Keith 2011-05-31 12:50:12

+0

錯過了那個,太過於放大(1,1,1,null)的東西。 – Johan 2011-05-31 12:52:01

+0

順便說一句,您可以通過別名進行排序,您不必在按順序排列的子句中重複表達式。它會加速事情。 – Johan 2011-05-31 12:53:11

1

不要使用SUM(空)的SUM(1,1,1,空)= NULL,而不是3.

SELECT s.*, s.yes+s.no+s.other as all FROM (
    SELECT Username, 
    SUM(CASE WHEN type = 'Yes' THEN 1 ELSE 0 END) as Yes, 
    SUM(CASE WHEN type = 'No' THEN 1 ELSE 0 END) as No, 
    SUM(CASE WHEN type = '' THEN 1 ELSE 0 END) as Other 
    FROM table 
    WHERE source = 'CompanyName' 
    GROUP BY Username 
) s 
ORDER BY all DESC 
+0

感謝您的建議。總數呢? – user622378 2011-05-31 12:48:52

+0

對不起,'你回去吧。 – Johan 2011-05-31 12:50:55