PIVOT sql中的下表

时间:2018-08-10 10:50:52

标签: sql

反转关注表

ID  Name    Category    From Date   To Date
1   A         X         1/20/2018   2/20/2018
2   A         Y         3/20/2018   4/20/2018
3   B         X         5/20/2018   6/20/2018
4   B         Y         7/20/2018   8/20/2018

ID  Name   X From Date  X To Date   Y From Date Y To Date
1   A      1/20/2018    2/20/2018   3/20/2018   4/20/2018
2   B      5/20/2018    6/20/2018   7/20/2018   8/20/2018

2 个答案:

答案 0 :(得分:1)

一种方法是简单的join

select row_number() over (order by name) as id,
       name,
       tx.fromdate as x_fromdate, tx.todate as x_todate,
       ty.fromdate as y_fromdate, ty.todate as y_todate
from t tx join
     t ty
     on tx.name = ty.name and tx.category = 'x' and ty.category = 'y';

答案 1 :(得分:0)

您可以进行有条件的聚合:

select row_number() over (order by name) as id, name,
       max(case when cat = 'X' then fromdate end),
       max(case when cat = 'X' then todate end),
       max(case when cat = 'Y' then fromdate end),
       max(case when cat = 'Y' then todate end)
from table t
group by name;