从每个领域获得总价值?

时间:2011-05-31 12:43:35

标签: mysql sql database

如何获取每个用户名的“是”,“否”,“其他”字段的总值?

我想添加总计字段。

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' ";

此外,最高总数排在最高位。

3 个答案:

答案 0 :(得分: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只能是'是','否'或''。

答案 1 :(得分: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

答案 2 :(得分:1)

不要使用SUM(null),(1,1,1,null)的SUM = 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