从表中为每种类型计算值

时间:2015-10-27 08:41:04

标签: sql sql-server sql-server-2008

我有下表 UserId [nvarchar(128)],Rating [varchar(170)]:值大多为1,2,3,但可以有异常

评级包含3个值[1,2或3]

我希望得到类似

的结果
{{1}}

是否可以在单个查询中

3 个答案:

答案 0 :(得分:2)

为每个用户ID执行GROUP BY UserId计数。使用CASE分别计算1,2和3:

select UserId,
       count(case when Rating = 1 then 1 end) as [Count(1's)],
       count(case when Rating = 2 then 1 end) as [Count(2's)],
       count(case when Rating = 3 then 1 end) as [Count(3's)]
from tablename
group by UserId

答案 1 :(得分:0)

在每个CASECOUNT UserId中使用GROUP BY语句。

SELECT UserId, COUNT(CASE WHEN value = '1' THEN 1 END) AS [Count(1's)], COUNT(CASE WHEN value = '2' THEN 1 END) AS [Count(2's)], COUNT(CASE WHEN value = '3' THEN 1 END) AS [Count(3's)]
FROM yourtable
GROUP BY UserId

答案 2 :(得分:0)

使用PIVOT

SELECT
  UserId, 
  COALESCE([1],0) [Count(1's)],
  COALESCE([2],0) [Count(2's)],
  COALESCE([3],0) [Count(3's)]
FROM
  ýour_table
PIVOT
  (COUNT([Rating])  
FOR Rating
  in([1],[2],[3])  
  )AS p
ORDER BY 
  UserId