简体   繁体   English

使用案例表达式的SQL查询

[英]SQL query using case expression

Let's say I have the following table 假设我有下表

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

And I want to generate the following table using an SQL query 我想使用SQL查询生成下表

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

I am trying to achieve this by the following code but that's not working. 我正在尝试通过以下代码来实现这一目标,但这是行不通的。 I understand why and can think of a solution using a left join but I am tempted to think that there is a smarter solution out there 我理解为什么并且可以想到使用左联接的解决方案,但是我很想认为那里有一个更聪明的解决方案

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

FROM new_table

Any ideas? 有任何想法吗?

Just add aggregation 只需添加聚合

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

SQL Fiddle SQL小提琴

MS SQL Server 2017 Schema Setup : 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)
;

Query 1 : 查询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 |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM