【问题标题】:GROUP BY on a column to get remove nulls对列进行 GROUP BY 以删除空值
【发布时间】:2019-12-10 17:07:34
【问题描述】:

我有下表

Order_ID  Loc_ID   OrderDate    ShippingDate  DeliveryDate
10           2      10/12/2018   null          null
10           2      null         null          18/12/2018
10           2      null         12/13/2019     null

基本上,每次记录日期时,都会将其添加为一行。我希望表格看起来像这样:

Order_ID   Loc_ID  Order_Date     ShippingDate   DeliveryDate
10            2    10/12/2018     13/12/2018     18/12/2018 

谁能告诉我该怎么做?

【问题讨论】:

  • 您希望表格看起来像这样,还是结果集看起来像这样?如果是前者,您可能想查看 UPDATE;如果是后者,已经提供的答案涵盖了这一点。
  • 那么您应该在代码中使用 UNPDATE,而不是 INSERT。

标签: sql-server


【解决方案1】:

使用MAX:

SELECT Order_ID,
       Loc_ID,
       MAX(OrderDate) AS OrderDate,
       MAX(ShippingDate) AS ShippingDate,
       MAX(DeliveryDate) AS DeliveryDate
FROM dbo.YourTable
GROUP BY Order_ID,
         Loc_ID;

当排序数据时NULL 具有最低值,因此任何非NULL 值将具有“更大”值。因此MAX 将返回非NULL 值。

【讨论】:

    【解决方案2】:

    一个简单的聚合应该可以解决问题

    示例

    Select Order_ID  
          ,Loc_ID   
          ,OrderDate    = max(OrderDate)
          ,ShippingDate = max(ShippingDate)
          ,DeliveryDate = max(DeliveryDate)
     From  YourTable
     Group By Order_ID,Loc_ID
    

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      • 2021-12-08
      相关资源
      最近更新 更多