根据公共值合并 SQL 中的行

Combining Rows in SQL Based on Common Values

我有一个州列表,每个州都有一个计数。我想合并共享相似状态的行,以便每个状态只有 1 行并且计数是数字或 null。

查询

select COALESCE(t1.State, t2.State, t3.State) AS 'State', t1.DMECount, t2.TransCount, t3.ProCount 
from #TestTable t1
FULL OUTER JOIN #TestTable2 t2 ON t1.State = t2.State
FULL OUTER JOIN #TestTable3 t3 ON t2.State = t3.State
ORDER BY 'State'

当前结果

State|DMECount|TransCount|ProCount
MA   |19      |NULL      |NULL
MA   |NULL    |NULL      |1
MD   |NULL    |NULL      |1
MD   |8       |NULL      |NULL
MI   |1450    |1         |259
MN   |21      |NULL      |NULL
MN   |NULL    |NULL      |2

想要的结果

State|DMECount|TransCount|ProCount
MA   |19      |NULL      |1
MD   |8       |NULL      |1
MI   |1450    |1         |259
MN   |21      |NULL      |2

从我看过的其他解决方案来看,似乎按状态分组并取其他解决方案的 MAX 可能会满足我的需要,但我无法按使用了 COALESCE 的字段进行分组。正在使用 COALESCE,这样如果其中一个表具有其他表没有的状态,状态列将使用该值而不是 NULL。

您只需在 GROUP BY 子句中包含 COALSCE 语句:

select COALESCE(t1.State, t2.State, t3.State) AS 'State', max(t1.DMECount), max(t2.TransCount), Max(t3.ProCount)
from #TestTable t1
FULL OUTER JOIN #TestTable2 t2 ON t1.State = t2.State
FULL OUTER JOIN #TestTable3 t3 ON t2.State = t3.State
GROUP BY COALESCE(t1.State, t2.State, t3.State)
ORDER BY COALESCE(t1.State, t2.State, t3.State)