TSQL - CASE创建两列一列

时间:2015-10-23 06:07:32

标签: sql-server tsql case

对于这个简化的表结构(参见fiddle),我需要删除为同一个ID输出的第二行。对于单个ID,行值可能只是“1”。

    CREATE TABLE lookup 
    (
     id int, 
     field varchar(20), 
     row varchar(20),
     value varchar(50)
    );

INSERT INTO lookup
(id,field, row, value)
VALUES
(1,'55', '1', '1XYZ'),
(1,'55', '2', '2XYZ'),
(2,'55', '1', '3XYZ');


CREATE TABLE output 
    (
     id int, 
     value_1 varchar(50),
     value_2 varchar(50)
    );

INSERT INTO output
(id, value_1, value_2)
VALUES
(1, '1XYZ', '2XYZ'),
(2, '3XYZ', null);


-- wrong
select id
,case when (field = 55 and row = 1) then value END AS value_1
,case when (field = 55 and row = 2) then value END AS value_2
from lookup;

希望你能告诉我如何。

谢谢。

1 个答案:

答案 0 :(得分:4)

只需在查询中添加聚合:

select id
,max(case when (field = 55 and row = 1) then value END) AS value_1
,max(case when (field = 55 and row = 2) then value END) AS value_2
from lookup
group by id;

Demo here