旋转表格以及总计

时间:2017-02-01 07:09:36

标签: sql-server

我有一张包含这些数据的表格

+------------+----------------+------------+
| Department | ProgressStatus | TasksCount |
+------------+----------------+------------+
| A          | Completed      |          1 |
| C          | Completed      |          4 |
| D          | Completed      |          1 |
| B          | Pending        |          8 |
| A          | Pending        |         10 |
| C          | Pending        |         12 |
| D          | Pending        |          2 |
| C          | Progress       |          4 |
+------------+----------------+------------+

我需要编写一个查询来获取这些输出(它看起来像一个简单的数据透视表)。

+-------------+-----------+---------+----------+--------------+
| Departments | Completed | Pending | Progress | Total Tasks  |
+-------------+-----------+---------+----------+--------------+
| A           |         1 |      10 |        0 |           11 |
| B           |         0 |       8 |          |            8 |
| C           |         4 |      12 |        4 |           20 |
| D           |         1 |       2 |          |            3 |
+-------------+-----------+---------+----------+--------------+

2 个答案:

答案 0 :(得分:4)

使用条件SUM和GROUP BY

select
    department,
    sum(case when ProgressStatus = 'Completed' then TasksCount end) Completed,
    sum(case when ProgressStatus = 'Pending' then TasksCount end) Pending,
    sum(case when ProgressStatus = 'Progress' then TasksCount end) Progress,
    sum(TasksCount) Total
from your_table
group by department;

答案 1 :(得分:0)

BY using pivot i tried like this 

SELECT  Department,isnull(Completed,0) Completed,isnull([Pending],0) [Pending],isnull([Progress],0) [Progress]
          ,isnull(Completed,0)+isnull([Pending],0)+isnull([Progress],0) as 'total'
    FROM #Table2
    PIVOT ( sum([TasksCount])
      for [ProgressStatus] in ([Completed], [Pending], [Progress])) AS pvt

输出

Department  Completed   Pending Progress    total
A                1       10       0          11
B                0       8        0           8
C                4      12        4          20
D                1      2         0           3