SQL Server:分组,合并并选择coalesce'd之一

时间:2017-04-26 13:53:08

标签: sql sql-server

我有一个名为Regions的表格:

city        district1   district2   district3   district4
---------------------------------------------------------
Michigan    2           NULL        NULL        2
Michigan    2           20          NULL        20
Michigan    2           NULL        3           3
Ontario     3           NULL        NULL        3
Quebec      4           1           NULL        1
Quebec      4           NULL        NULL        4
Edmonton    NULL        7           NULL        7
Edmonton    NULL        NULL        11          11

district4(coalesce(district3, district2, district1))

而且我想得到一个与城市分开的区域分区

city        district1   district_final
--------------------------------------    
Michigan    2           3
Ontario     3           3
Quebec      4           1
Edmonton    NULL        11

district_final不是最大值;这是团队的合并

2 个答案:

答案 0 :(得分:0)

以下代码应解决我猜的目的:

 SELECT CITY,dct1 as district1,MAX(DCT) as district_final FROM
(
SELECT CITY, district1 as dct1, district1 AS DCT FROM [TABLE] 
UNION
SELECT CITY, district1 as dct1, district2 AS DCT FROM [TABLE] 
UNION
SELECT CITY, district1 as dct1, district3 AS DCT FROM [TABLE] 
) tempTable
group by CITY,dct1;

答案 1 :(得分:0)

select distinct r1.city, r1.district1,  coalesce(r3.district3, r2.district2, r1.district1) district_final
from Regions r1
left outer join Regions r2 on r1.city = r2.city and r2.district2 is not null
left outer join Regions r3 on r1.city = r3.city and r3.district3 is not null