基于列中的值对内连接的值求和

时间:2018-01-25 03:54:20

标签: sql postgresql

我有一个结构如下的预订表:

date        activity_id  state     pax  ...
----------  -----------  --------  ---
2018-01-01  1            accepted  2
2018-01-01  1            accepted  4
2018-01-01  1            pending   1
2018-01-01  2            accepted  3

我想查找每个日期和类别具有接受或待处理状态的人数。对于给定的行,结果应为:

date        activity_id  accepted  pending
----------  -----------  --------  ---
2018-01-01  1            6         1
2018-01-01  2            3         0

我不关心其他州,只接受和待决。

只接受或仅接受预订很简单:

SELECT date, activity_id, SUM(pax) AS accepted
FROM bookings
WHERE state = 'accepted'
GROUP BY date, activity_id

我尝试使用类似的东西同时获得两者:

SELECT b1.date, b1.activity_id, SUM(b1.pax) AS accepted, SUM(b2.pax) AS pending
FROM bookings b1
JOIN bookings b2 ON b1.date = b2.date AND b1.activity_id = b2.activity_id
WHERE b1.state = 'accepted' AND b2.state = 'pending'
GROUP BY b1.date, b1.activity_id

但是只有在接受预订和待定预订的情况下才会有效,并且待处理的计数有时会被取消。

1 个答案:

答案 0 :(得分:0)

您想要条件聚合:

SELECT date, activity_id,
       SUM(case when state = 'accepted' then pax else 0 end) AS accepted,
       SUM(case when state = 'pending' then pax else 0 end) AS pending
FROM bookings
WHERE state in ('accepted', 'pending')
GROUP BY date, activity_id
ORDER BY date, activity_id;

严格地说,WHERE条款不是必需的。但是如果你有很多其他状态,那么聚合之前的过滤可以使性能受益。

相关问题