如何有条件地从选择查询中转置数据

时间:2018-08-22 05:03:51

标签: sql

我有一个选择查询,它向我返回如下数据:

---------------------------------------
PartCode  | ParentCode  |  Flag  |
---------------------------------------
ABC       |  XYZ        |  null  |
---------------------------------------
PQR       |  XYZ        |   Y    |
---------------------------------------

现在,我想根据以下标志进行转置:

-标记为Y的PartCode应该标记为criticalPart,其他标记为SecondaryPart。

-总是有两行要应用此条件。

---------------------------------------------
ParentCode | CriticalPart  |  SecondaryPart |
---------------------------------------------
XYZ        |  PQR          |    ABC         |
---------------------------------------------

2 个答案:

答案 0 :(得分:3)

使用下面的代码获得结果。

  select ParentCode
    , Max(case when flag = 'Y' then PartCode end) as CriticalPart
    , Max(case when flag is null then PartCode end) as SecondaryPart
    from table 
    group by ParentCode

SQL Fiddle Link

答案 1 :(得分:1)

我将使用两个子查询和一个父代码联接

SELECT  critical.ParentCode, 
        critical.PartCode as CriticalPart, 
        secondary.PartCode as SecondaryPart
    FROM (
        SELECT  ParentCode, PartCode 
            FROM Table 
            WHERE Flag IS NOT NULL
    ) critical
    INNER JOIN (
        SELECT ParentCode, PartCode 
            FROM Table 
            WHERE Flag IS NULL
    ) secondary ON critical.ParentCode = secondary.ParentCode