如何将同一个表中的行拆分成列?

时间:2018-05-04 19:09:24

标签: sql sql-server tsql

假设我有一个非常简单的表:

enter image description here

我想要一个查询将这些数据返回到一行,如下所示:

enter image description here

我该怎么做呢?这是我到目前为止所尝试的内容:

SELECT
    od.OrderNo,
    CASE
        WHEN od.PartNo LIKE 'CAD%' THEN od.PartNo
        END AS [Part1],
    CASE
        WHEN od.PartNo LIKE 'CAD%' THEN od.DueDate
        END AS [DueDate1],
    CASE
        WHEN od.PartNo LIKE 'WISH%' THEN od.PartNo
        END AS [Part2],
    CASE
        WHEN od.PartNo LIKE 'WISH%' THEN od.DueDate
        END AS [DueDate2]
FROM OrderDet od
WHERE od.OrderNo = '20352E'
    AND (od.PartNo LIKE 'CAD%'
    OR od.PartNo LIKE 'WISH%')

我从中得到的结果如下:

enter image description here

我也尝试过自我加入,就像这样:

SELECT
    od.OrderNo,
    od.PartNo AS [Part1],
    od.DueDate AS [DueDate1],
    od2.PartNo AS [Part2],
    od2.DueDate AS [DueDate2]
FROM OrderDet od
    JOIN OrderDet od2 ON od.OrderNo = od2.OrderNo
WHERE od.OrderNo = '20352E'
    AND (od.PartNo LIKE 'CAD%'
    OR od2.PartNo LIKE 'WISH%')

那也没用,但是,第8行是我想要的,只是不确定如何隔离,结果如下:

enter image description here

那么有没有办法真正做我想要的并让它显示在一行?无法绕过它。感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:1)

使用group by子句并执行条件聚合

select OrderNo,
       max(case when PartNo LIKE 'CAD%' then 'CAD' end) as PartNo1,
       max(case when PartNo LIKE 'CAD%' then DueDate end) as DueDate1,
       max(case when PartNo LIKE 'WISH%' then 'WISH' end) as PartNo2,
       max(case when PartNo LIKE 'WISH%' then DueDate end) as DueDate2
from OrderDet o
where OrderNo = '20352E' and 
      (PartNo LIKE 'CAD%' or PartNo LIKE 'WISH%')
group by OrderNo; 

答案 1 :(得分:0)

这个怎么样:

ibm_boto3