1

我已经为此搜索了答案,但找不到完全根据条件获取此不同记录集的方法。我有一个包含以下示例数据的表:

+---------+-------------+
| 分行 | 任务状态 |
+---------+-------------+
| 帐户 | 已完成 |
| 人力资源 | 已完成 |
| 帐户 | 已完成 |
| 人力资源 | 未定义 |
| 帐户 | 未完成 |
| 帐户 | 未定义 |
| 帐户 | 已完成 |
| 人力资源 | 未完成 |
| 人力资源 | 未完成 |
| 人力资源 | 已完成 |
| 人力资源 | 未定义 |
+---------+-------------+

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

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

5 回答 5

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
于 2013-04-29T12:32:18.840 回答
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
于 2013-04-29T12:32:14.010 回答
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;
于 2013-04-29T12:34:32.740 回答
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
于 2013-04-29T12:35:05.990 回答
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上的演示

于 2013-04-29T13:03:08.657 回答