使用case表达式的SQL查询

时间:2018-02-15 07:37:39

标签: sql case

假设我有下表

+----------+--------+-------+-------+
| Employee | Day    | Task  | Hours |
+----------+--------+-------+-------+
| Chip     | 01 Jan | TaskA | 2     |
+----------+--------+-------+-------+
| Chip     | 01 Jan | TaskB | 3     |
+----------+--------+-------+-------+
| Chip     | 02 Jan | TaskB | 4     |
+----------+--------+-------+-------+

我想使用SQL查询生成下表

+----------+--------+-------------+
| Employee | Day    | TaskA_Hours |
+----------+--------+-------------+
| Chip     | 01 Jan | 2           |
+----------+--------+-------------+
| Chip     | 02 Jan | null        |
+----------+--------+-------------+

我试图通过以下代码实现这一点,但这不起作用。我理解为什么并且可以考虑使用左连接的解决方案,但我很想认为那里有一个更聪明的解决方案

SELECT 
Employee,
Day,
CASE when Task = 'TaskA' THEN Hours ELSE null END AS TaskA_Hours

FROM new_table

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

只需添加汇总

SELECT 
  Employee,
  Day,
  SUM(CASE when Task = 'TaskA' THEN Hours END) AS TaskA_Hours
FROM new_table
GROUP BY Employee, Day

答案 1 :(得分:0)

SQL Fiddle

MS SQL Server 2017架构设置

CREATE TABLE new_table
    ([Employee] varchar(4), [Day] varchar(10), [Task] varchar(5), [Hours] int)
;

INSERT INTO new_table
    ([Employee], [Day], [Task], [Hours])
VALUES
    ('Chip', '01 Jan', 'TaskA', 2),
    ('Chip', '01 Jan', 'TaskB', 3),
    ('Chip', '02 Jan', 'TaskB', 4)
;

查询1

SELECT 
  Employee,
  Day,
  SUM(CASE when Task = 'TaskA' THEN Hours END) AS TaskA_Hours,
  SUM(CASE when Task = 'TaskB' THEN Hours END) AS TaskB_Hours
FROM new_table
GROUP BY Employee, Day

<强> Results

| Employee |    Day | TaskA_Hours | TaskB_Hours |
|----------|--------|-------------|-------------|
|     Chip | 01 Jan |           2 |           3 |
|     Chip | 02 Jan |      (null) |           4 |