Sql 如何有条件地转换select查询中的数据
我有一个select查询,它按如下方式返回我的数据:Sql 如何有条件地转换select查询中的数据,sql,Sql,我有一个select查询,它按如下方式返回我的数据: --------------------------------------- PartCode | ParentCode | Flag | --------------------------------------- ABC | XYZ | null | --------------------------------------- PQR | XYZ | Y
---------------------------------------
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
聚合函数,智能!聚合函数,智能!