确定哪些用户在SQL中每天都有正余额

确定哪些用户在SQL中每天都有正余额,sql,postgresql,google-bigquery,Sql,Postgresql,Google Bigquery,我在银行中有来自以下模式的多个用户的用户交易数据: 如果不存在事务,则创建表( id int, 用户id int, 于年月日创建, 浮动金额 ); 在事务中插入值 (1, 1, '2020-01-01', 100), (2, 1, '2020-01-02', -50), (3, 1, '2020-01-04', -50), (4, 2, '2020-01-04', 80), (5, 3, '2020-01-06', 10), (6, 3, '2020-01-10', -10); 我想知道,从交

我在银行中有来自以下模式的多个用户的用户交易数据:

如果不存在事务,则创建表(
id int,
用户id int,
于年月日创建,
浮动金额
);
在事务中插入值
(1, 1, '2020-01-01', 100),
(2, 1, '2020-01-02', -50),
(3, 1, '2020-01-04', -50),
(4, 2, '2020-01-04', 80),
(5, 3, '2020-01-06', 10),
(6, 3, '2020-01-10', -10);
我想知道,从交易开始到当前日期的每一天,哪些用户的账户上都有正余额

在这种情况下,查询的输出将是:

date,user_id
'2020-01-01',1
'2020-01-02',1
'2020-01-03',1
'2020-01-04',1
'2020-01-04',2
'2020-01-05',2
'2020-01-06',2
'2020-01-07',2
...
'2021-05-17',2 -- Today's date, user 2 still has positive balance
'2020-01-06',3
'2020-01-07',3
'2020-01-08',3
'2020-01-09',3
'2020-01-10',3
使用PostgreSQL有没有一种简单的方法可以做到这一点?或者更好,在BigQuery中?

在BigQuery中尝试以下操作:

with transactions as (
  select 1 as user_id, date '2020-01-01' as date, 100 as amount union all
  select 1, '2020-01-02', -50 union all
  select 1, '2020-01-04', -50 union all
  select 2, '2020-01-04', 80 union all
  select 3, '2020-01-06', 10 union all
  select 3, '2020-01-10', -10
),
all_users as (
  select min(date) as min_date, user_id
  from transactions
  group by user_id
),
all_days as (
  select *
  from all_users, unnest(generate_date_array('2020-01-01', current_date())) as date
  where date >= min_date
)
select date, user_id
from all_days left join transactions using (user_id, date)
where true
qualify sum(amount) over (partition by user_id order by date) > 0
没有
的情况下,请确认

with transactions as (
  select 1 as user_id, date '2020-01-01' as date, 100 as amount union all
  select 1, '2020-01-02', -50 union all
  select 1, '2020-01-04', -50 union all
  select 2, '2020-01-04', 80 union all
  select 3, '2020-01-06', 10 union all
  select 3, '2020-01-10', -10
),
all_users as (
  select min(date) as min_date, user_id
  from transactions
  group by user_id
),
all_days as (
  select *
  from all_users, unnest(generate_date_array('2020-01-01', current_date())) as date
  where date >= min_date
)
select date, user_id
from (
  select date, user_id, sum(amount) over (partition by user_id order by date) as balance
  from all_days left join transactions using (user_id, date)
)
where balance > 0

由于某些原因,我无法在BQ中的交易表上使用
qualify
,在您的示例中,我可以这样做而不使用该表吗?
qualify
是最近发布的一项新功能。添加了没有它的示例。