SELECT DISTINCT HAVING计算独特条件

时间:2013-04-29 12:29:31

标签: sql

我已经搜索过这方面的答案,但却找不到如何根据条件得到这个独特的记录集。我有一个包含以下示例数据的表:

+---------+-------------+
| Branch  | Task Status |
+---------+-------------+
| Account | Completed   |
| HR      | Completed   |
| Account | Completed   |
| HR      | Not Define  |
| Account | Uncompleted |
| Account | Not Define  |
| Account | Completed   |
| HR      | Uncompleted |
| HR      | Uncompleted |
| HR      | Completed   |
| HR      | Not Define  |
+---------+-------------+

我想创建一个查询,显示总任务的数量,并且还需要总共任务状态明智的任务数,例如

Branch  Total Task  Completed   Uncompleted Not Define
Account       5            3        1         1
Admin         6            2        2         2

5 个答案:

答案 0 :(得分:2)

SELECT  branch,
        COUNT(*),
        SUM(CASE status WHEN 'completed' THEN 1 END) AS completed,
        SUM(CASE status WHEN 'uncompleted' THEN 1 END) AS uncompleted,
        SUM(CASE status WHEN 'not define' THEN 1 END) AS not_define
FROM    task
GROUP BY
        branch

答案 1 :(得分:1)

SELECT Branch
     , COUNT(1) as Total
     , COUNT(CASE WHEN TaskStatus = 'Completed' THEN 1 ELSE 0 END) AS Completed
     , COUNT(CASE WHEN TaskStatus = 'Uncompleted' THEN 1 ELSE 0 END) AS Uncompleted
     , COUNT(CASE WHEN TaskStatus = 'Not Define' THEN 1 ELSE 0 END) AS NotDefine
FROM Table
GROUP BY Branch

答案 2 :(得分:1)

SELECT branch,
COUNT(*),
COUNT(CASE taskstatus WHEN 'Completed' THEN 1 END),
COUNT(CASE taskstatus WHEN 'Uncompleted' THEN 1 END),
COUNT(CASE taskstatus WHEN 'Not Define' THEN 1 END)
FROM YourTable
GROUP BY branch;

答案 3 :(得分:0)

试试这个

SELECT * FROM (SELECT 
ROW_NUMBER() OVER(PARTITION BY Branch ORDER BY [Task Status]) AS No,
Branch,
sum (CASE WHEN [Task Status] = 'Completed' THEN 1 ELSE 0 END ) OVER (PARTITION BY Branch) AS [Completed],
sum (CASE WHEN [Task Status] = 'Not Define' THEN 1 ELSE 0 END ) OVER (PARTITION BY Branch) AS [Not Define],
sum (CASE WHEN [Task Status] = 'Uncompleted' THEN 1 ELSE 0 END ) OVER (PARTITION BY Branch) AS [Uncompleted]
 FROM task ) AS T1 WHERE No = 1

SELECT * FROM (SELECT 
ROW_NUMBER() OVER(PARTITION BY Branch ORDER BY [Task Status]) AS No,
Branch,
count (CASE WHEN [Task Status] = 'Completed' THEN 1 ELSE 0 END ) OVER (PARTITION BY Branch) AS [Completed],
count (CASE WHEN [Task Status] = 'Not Define' THEN 1 ELSE 0 END ) OVER (PARTITION BY Branch) AS [Not Define],
count (CASE WHEN [Task Status] = 'Uncompleted' THEN 1 ELSE 0 END ) OVER (PARTITION BY Branch) AS [Uncompleted]
 FROM task ) AS T1 WHERE No = 1

答案 4 :(得分:0)

在SQL Server2005 +中,您可以使用PIVOT运算符

SELECT *
FROM (
      SELECT *, COUNT(*) OVER(PARTITION BY Branch) AS TotalTask
      FROM dbo.task
      ) p    
PIVOT
 (
  COUNT(p.Task) FOR p.Task IN ([Completed], [Uncompleted], [Not Define])
  ) x

SQLFiddle上的演示