把一些类别作为列名

Put some categories as column names

我有一个 table 看起来像这样:

Month Region Category Size Brand Price
January Canada T-shirts S Nike 100
January Canada T-shirts S Reebok 150
January Canada T-shirts S Puma 200
January Canada Jacket S Nike 200
January Canada Jacket S Reebok 300
January USA Jacket L Puma 400
January USA Jacket L Reebok 500
  1. 我想让 table 看起来像这样(不需要聚合函数):
Month Region Category Size Nike Reebok Puma
January Canada T-shirts S 100 150 200
January Canada Jacket S 400 300 NULL
January USA Jacket L NULL 500 400
  1. 我想要 select 具有相同月份、地区、类别和尺码值的行,耐克价格高于其他任何价格。对于 table 上面的结果应该是:
Month Region Category Size Nike Reebok Puma
January Canada Jacket S 400 300 NULL

您似乎需要条件聚合然后进行一些过滤。

select *
from (select Month, Region, Category, Size,  
             max(case when brand = 'Nike' then price end) as nike, 
             max(case when brand = 'Reebok' then price end) as Reebok, 
             max(case when brand = 'Puma' then price end) as Puma           
      from t
      group by Month, Region, Category, Size
     ) t
where nike > coalesce(Reebok, 0) and
      nike > coalesce(Puma, 0);