选择具有不同值的相同列的计数

时间:2018-03-09 04:39:20

标签: sql sql-server tsql

我有这样的选择:

SELECT 
    [Status] AS Requested
    ,[Status] AS [Sent]
    ,[Status] AS Finished
     FROM Store.[Order] 

Status是一个int值,我想要Count all Status

  1. 计算值= 1并显示为请求值。
  2. 计数值= 2并显示为已发送。
  3. 计数值= 3并显示为已完成。
  4. 我怎样才能实现它?此致

1 个答案:

答案 0 :(得分:2)

使用case表达式根据值( 1,2,3 )计算状态

SELECT 
       SUM(CASE WHEN [Status] = 1 THEN 1 ELSE 0 END) AS Requested,
       SUM(CASE WHEN [Status] = 2 THEN 1 ELSE 0 END) AS Sent,
       SUM(CASE WHEN [Status] = 3 THEN 1 ELSE 0 END) AS Finished
FROM Store.[Order]