【问题标题】:SQL Server Combine Duplicate EntriesSQL Server 合并重复条目
【发布时间】:2021-12-31 17:11:33
【问题描述】:

我有一个包含以下数据的 Microsoft SQL 表:

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

我希望能够查询此表并仅返回 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

返回

CustomerID   L1   L2
788          B    B
649          B
936          B

很难解决这个问题。任何帮助将不胜感激。

【问题讨论】:

  • 也许您可以稍微整合一下您的想法,并分享您迄今为止尝试过的事情以及出了什么问题。
  • Select Distinct CustomerID, COALESCE(Location1, Location2) 排序的作品,但我最终得到 788 A 788 B 649 A 649 B 936 B
  • @BarbarosÖzhan coalesce 的解决方案是什么??
  • 那也不是真正的工作。我得到 788 B B
  • @JamesBrown 如果有 (111, 11, null) 和 (111, 12, null),应该选择哪一个?

标签: sql sql-server tsql


【解决方案1】:

这应该可以解决 OP 的最后一个 cmets:

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

【讨论】:

    【解决方案2】:

    使用最小值和最大值:

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

    【讨论】:

    • 谢谢@eshirvana!这几乎行得通。我有一些值,例如 CustomerID Location1 Location2 1674 A NULL 1674 B NULL
    • @JamesBrown 这个怎么样,查看更新的答案,
    • 我可以使用它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2012-09-25
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多