PLSQL查询一个变量并分成两列

时间:2017-04-20 15:30:41

标签: sql oracle plsql conditional-aggregation

所以我有一个名为Table1的表,有两列,Product和indicator。

Table1

Product    Indicator
Product 1     Y
Product 1     Y
Product 1     Y
Product 1     N
Product 1     N
Product 2     Y
Product 2     Y
Product 2     Y
Product 2     Y
Product 2     Y

我希望能够运行查询来显示这样的结果

            Indicator = Y   Indicator = N
Product 1        Y               Y
Product 2        Y               N

提前致谢! :)

1 个答案:

答案 0 :(得分:4)

不需要PL / SQL,这可以使用纯SQL进行,使用条件聚合。

select product, 
       case 
         when count(case when indicator = 'Y' then 1 end) > 0 then 'Y'
         else 'N'
       end as "Indicator = Y",
       case 
         when count(case when indicator = 'N' then 1 end) > 0 then 'Y'
         else 'N'
       end as "Indicator = N"
from table1
group by product
order by product;