SQL 服务器合并重复条目

SQL Server Combine Duplicate Entries

我有一个 Microsoft SQL table,其中包含以下数据:

CustomerID   Location1   Location2
788          A           NULL
788          A           B
788          B           NULL
649          A           NULL
649          NULL        B
936          B           NULL

我希望能够仅查询此 table 和 return CustomerID 以及组合的唯一位置。

CustomerID   Location1   Location2
788          A           B
649          A           B
936          B
Select Distinct CustomerID, MAX(Location1) L1, MAX(Location2) L2
FROM table
GROUP BY CustomerID

returns

CustomerID   L1   L2
788          B    B
649          B
936          B

很难解决这个问题。如有任何帮助,我们将不胜感激。

使用最小值和最大值:

Select CustomerID
       , MIN(coalesce(Location1,Location2)) L1
       , MAX(coalesce(Location2,Location1)) L2
FROM table
GROUP BY CustomerID

这应该可以解决 OP 的最后评论:

with u as
(select CustomerID, Location1 as L
from Table1
where Location1 is not null
union select CustomerID, Location2 as L 
from Table1
where Location2 is not null)
(select customerID, min(L) as Location1, case when max(L) <> min(L) then max(L) end as Location2
from u
group by CustomerID)

Fiddle

或使用其他答案中的相同技巧:

Select CustomerID
       , MIN(coalesce(Location1,Location2)) L1
       , case when MAX(coalesce(Location2,Location1)) <> MIN(coalesce(Location1,Location2)) then MAX(coalesce(Location1,Location2)) end L2
FROM table
GROUP BY CustomerID