简体   繁体   English

根据列中的值对内部联接求和

[英]Summing values on inner join based on value in column

I have a bookings table that is structured like this: 我有一个预订表,其结构如下:

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

I want to find the number of people that have an accepted or pending state per date and category. 我想找到每个日期和类别处于接受或待处理状态的人数。 With the given rows, the result should be this: 对于给定的行,结果应为:

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

I don't care about other states, only accepted and pending. 我不在乎其他州,只在接受和等待中。

To get only accepted or only pending bookings is simple enough: 仅接受已接受或仅待处理的预订非常简单:

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

I tried to get both at the same time using something like this: 我试图使用以下方法同时获取两者:

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

but that only works for days when there are both accepted and pending bookings and the pending count seems to off sometimes. 但这仅适用于既有已接受预订又有待处理预订的几天,而待处理计数有时似乎会减少。

You want conditional aggregation: 您需要条件聚合:

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;

Strictly speaking, the WHERE clause is not necessary. 严格来说,不需要WHERE子句。 But if you have a lot of other states, then the filtering before the aggregation could benefit performance. 但是,如果您还有许多其他状态,则聚合之前的过滤可能会提高性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM