假设我有两个表分别包含:
| User | birthday |
| ----------- |:-------------:|
| 'you' | '1980-11-01' |
| 'me' | '1986-12-27' |
和
| Event | date_start | date_end |
| ------------ |:-------------:| ------------- |
| 'e1' | '1980-10-13' | '1980-12-01'
| 'e2' | '1986-01-04' | '1987-01-01'
| 'e3' | '2000-10-13' | '2003-12-01'
并且假设对于第二个表中的每个事件,我想选择生日落在其日期时间跨度之间的所有用户,这意味着在date_start
和date_end
之间的区间内。
显然,JOIN不适合这种需要,有办法吗?作为参考,我对在Redshift数据库上执行此操作特别感兴趣。
为什么加入还不够?
select *
from event e
join user u on e.date_start < u.birthday and e.date_end > u.birthday
您可以使用LISTAGG功能
select (select istagg(u.User) within group (order by u.User)
from user u
where
u.birthday >= ev.date_start and u.birthday < ev.date_end )
from event_table ev
也许这可以是一个解决方案:
SELECT
ev.name,
LISTAGG(user_name, ', ') WITHIN GROUP ( ORDER BY user_name DESC ) "Users"
FROM events ev
LEFT JOIN users u ON u.birthday >= ev.datestart AND u.birthday <= ev.dateend
GROUP BY ev.name;