【问题标题】:Combine two rows in table using one column data使用一列数据组合表中的两行
【发布时间】:2014-10-23 23:25:12
【问题描述】:

我有一张表,我想将两个单独的行合并为一行。这是一个将信息存储在不同行上的产品目录。这是示例数据和预期结果。

表名:ProductCatalog

Product_ID  | Action     | Date
-----------------------------------------
0001        | Added      | 12/11/1983
0001        | Removed    | 01/01/2003
0002        | Added      | 12/11/1983

预期结果:

Product_ID  | Added        | Removed
========================================
0001        | 12/11/1983   | 01/01/2003 
0002        | 12/11/1983   | null

我已尝试加入Product_ID 以使AddedRemoved 日期在新表或视图中并排显示,但我没有得到想要的结果。我没有使用MAX(column),因为我没有得到想要的结果,或者我分组错误。

【问题讨论】:

    标签: sql sql-server sql-server-2008


    【解决方案1】:

    我认为最简单的方法是条件聚合:

    select pc.product_id,
           max(case when pc.action = 'Added' then pc.[date] end) as Added,
           max(case when pc.action = 'Removed' then pc.[date] end) as Removed
    from ProductCatalog pc
    group by pc.product_id;
    

    您也可以使用pivot 执行此操作。

    【讨论】:

    • 这只是一个细节,但在引用表的列时使用声明的别名 pc 不是一个好习惯吗?
    【解决方案2】:

    首先您需要将数据放入两个单独的列中,然后您可以将其包装在子选择中并按Product_id 分组,因为只有AddedDateRemovedDate 中的一个具有价值我们可以使用MAX 函数来显示该数据,每个Product_ID 只产生 1 行

    SELECT Product_id
           ,MAX(AddedDate)
           ,MAX(RemovedDate)
        FROM (
               SELECT Product_ID
                   ,CASE WHEN [ACTION] = 'Added' THEN [date]
                         ELSE NULL
                    END AS AddedDate
                   ,CASE WHEN [ACTION] = 'Removed' THEN [date]
                         ELSE NULL
                    END AS RemovedDate
                FROM ProductCatalog
             ) a
        GROUP BY Product_id
    

    【讨论】:

      【解决方案3】:

      尝试类似(伪代码)

      Select a.ProductID, a.AddedDate, b.RemovedDate
        from table a, table b left outer join on a.ProductId = b.ProductID
       where a.tran = "Removed"
      

      【讨论】:

        【解决方案4】:
        select * from
        (select *from ProductCatalog)p
        pivot(max(Date1) for  Action1 in ([Added],[Removed]))as pvt
        

        【讨论】:

          猜你喜欢
          • 2021-04-03
          • 1970-01-01
          • 2020-04-11
          • 1970-01-01
          • 1970-01-01
          • 2022-08-11
          • 1970-01-01
          • 2015-04-22
          • 1970-01-01
          相关资源
          最近更新 更多