首页 > 解决方案 > 如何有条件地从选择查询中转置数据

问题描述

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

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

现在我想根据标志将其转置如下:

- 标记为 Y 的零件代码应标记为关键零件,其他零件标记为辅助零件。

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

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

标签: sql

解决方案


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

  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小提琴链接


推荐阅读