我想通过连接pgadmin中的两个表来创建数据透视表视图

时间:2017-06-21 08:37:25

标签: sql postgresql pivot-table

我想创建一个数据透视表视图,显示每个travel_mode的每月预订总和。

表1预订 - 时间戳,预订,provider_id 表2提供者 - provider_id,travel_mode

不要使用数据透视表功能和交叉表功能来执行此练习。我想要使​​用连接或其他功能。

我不了解我正在尝试运行的此查询的问题,它显示"关系x不存在"

SELECT c.month, train.amount, bus.amount, air.amount
FROM (SELECT x.month
      FROM (SELECT  to_char(date_,'month') as month, travel_mode, sum(bookings) as amount
    from bookings as b
    join providers as p
    on b.provider_id=p.provider_id
    group by month, travel_mode) x
      group by x.month
      ) c
JOIN x train ON c.month = train.month AND train.amount = 'train'
JOIN x bus ON c.month = bus.month AND bus.amount = 'bus'
JOIN x air ON c.month = air.month AND air.amount = 'air'
;

1 个答案:

答案 0 :(得分:0)

如果我剖析您的查询,我认为这就是您要做的事情:

with x as (
  SELECT  to_char(date_,'month') as month, travel_mode, sum(bookings) as amount
  from bookings as b
    join providers as p on b.provider_id=p.provider_id
  group by month, travel_mode) x
)
SELECT c.month, train.amount, bus.amount, air.amount
FROM (
    SELECT x.month
    FROM x
    group by x.month
) c  
  JOIN x train ON c.month = train.month AND train.amount = 'train'
  JOIN x bus ON c.month = bus.month AND bus.amount = 'bus'
  JOIN x air ON c.month = air.month AND air.amount = 'air'

如果要多次加入查询(派生表)的结果,则必须将其加入common table expression

select month from x group by month部分对我没有任何意义。