将行合并到列中

时间:2017-09-12 21:54:38

标签: postgresql pivot crosstab

我有一张类似的表:

 Match | Quarter | Profit
-------+---------+--------
   1   | First   | 10.00
   1   | Second  | 14.00
   2   | First   | 22.00
   1   | Last    | 11.00
   2   | Second  | 18.00
   2   | Third   | 16.00
   2   | Last    | 10.00

我想实现这个目标:

 Match | First Profit | Second Profit | Third Profit | Last Profit
-------+--------------+---------------+--------------+---------------
   1   | 10.00        | 14.00         |0.00          |11.00
   2   | 22.00        | 18.00         |16.00         |10.00

简单地说,将行合并为一行。重要的是,如果没有找到四分之一的值,则结果记录为0.00;

不确定如何使用CROSSTAB函数实现这一目标?

我已经阅读并努力寻找一个好的答案或解决方案。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这应该做:

SELECT Match
    , sum(case when Quarter = 'First' then Profit else 0.00 end) as first_profit
    , sum(case when Quarter = 'Second' then Profit else 0.00 end) as second_profit
    , sum(case when Quarter = 'Third' then Profit else 0.00 end) as third_profit
    , sum(case when Quarter = 'Last' then Profit else 0.00 end) as last_profit
FROM data
GROUP BY match
ORDER BY Match

以下是您的示例数据示例:

with data as (
select
1 as match, 'First' as Quarter, 10.00 as Profit
union
select
1 as match, 'Second' as Quarter, 14.00 as Profit
union
select
2 as match, 'First' as Quarter, 22.00 as Profit
union
select
1 as match, 'Last' as Quarter, 11.00 as Profit
union
select
2 as match, 'Second' as Quarter, 18.00 as Profit
union
select
2 as match, 'Third' as Quarter, 16.00 as Profit
union
select
2 as match, 'Last' as Quarter, 10.00 as Profit
)
SELECT Match
    , sum(case when Quarter = 'First' then Profit else 0.00 end) as first_profit
    , sum(case when Quarter = 'Second' then Profit else 0.00 end) as second_profit
    , sum(case when Quarter = 'Third' then Profit else 0.00 end) as third_profit
    , sum(case when Quarter = 'Last' then Profit else 0.00 end) as last_profit
FROM data
GROUP BY match
ORDER BY Match