Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何有条件地转换select查询中的数据_Sql - Fatal编程技术网

Sql 如何有条件地转换select查询中的数据

Sql 如何有条件地转换select查询中的数据,sql,Sql,我有一个select查询,它按如下方式返回我的数据: --------------------------------------- PartCode | ParentCode | Flag | --------------------------------------- ABC | XYZ | null | --------------------------------------- PQR | XYZ | Y

我有一个select查询,它按如下方式返回我的数据:

---------------------------------------
PartCode  | ParentCode  |  Flag  |
---------------------------------------
ABC       |  XYZ        |  null  |
---------------------------------------
PQR       |  XYZ        |   Y    |
---------------------------------------
现在,我想根据以下标志将其转置:

---------------------------------------
PartCode  | ParentCode  |  Flag  |
---------------------------------------
ABC       |  XYZ        |  null  |
---------------------------------------
PQR       |  XYZ        |   Y    |
---------------------------------------
-标记为Y的零件代码应标记为criticalPart,其他标记为SecondaryPart

-总是有两行我想应用这个条件

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

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

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

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

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

使用下面的代码来实现结果

  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

使用下面的代码来实现结果

  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

聚合函数,智能!聚合函数,智能!