TSQL:列和行值的表示

时间:2017-06-25 02:56:39

标签: tsql sql-server-2012

我有一个场景,其中从表中提取的数据如下

EMP_Name Total_Work Work_Classification Work_Type
SAM         10          Shift               1
SAM         20          Shift               2
SAM         40          Shift               3
SAM         80          Day                 NULL
TIM         12          Shift               1
TIM         18          Shift               2
TIM         22          Shift               3
TIM         41          Day                 NULL
John        21          Shift               1
John        17          Shift               2
John        31          Shift               3
John        76          Day                 NULL

数据需要表示如下,

EMP_Name Total_Work_Day Work_Type1 Work_Type2 Work_Type3
SAM         80          10          20          40
TIM         41          12          18          22
John        76          21          17          31

请帮我解决使用TSQL表示数据的问题

1 个答案:

答案 0 :(得分:1)

您可以通过合并SUMCASE语句来获得结果。我按Work_Type1排序,但您可以根据需要更改或删除ORDER BY

SELECT EMP_Name,
  SUM(CASE WHEN Work_Classification = 'Day' THEN Total_Work ELSE 0 END) AS 'Total_Work_Day',
  SUM(CASE WHEN Work_Type = 1 THEN Total_Work ELSE 0 END) AS 'Work_Type1',
  SUM(CASE WHEN Work_Type = 2 THEN Total_Work ELSE 0 END) AS 'Work_Type2',
  SUM(CASE WHEN Work_Type = 3 THEN Total_Work ELSE 0 END) AS 'Work_Type3'
FROM Table_1
GROUP BY EMP_Name
ORDER BY SUM(CASE WHEN Work_Type = 1 THEN Total_Work ELSE 0 END)

结果:

+-----------------------------------------------------------------+
|EMP_Name | Total_Work_Day | Work_Type1 | Work_Type2 | Work_Type3 |
+-----------------------------------------------------------------+
|  SAM    |      80        |    10      |    20      |    40      |
|  TIM    |      41        |    12      |    18      |    22      |
|  JOHN   |      76        |    21      |    17      |    31      |
+-----------------------------------------------------------------+