gpt4 book ai didi

sql - 选择计数、内部连接和 where 语句

转载 作者:行者123 更新时间:2023-11-29 14:09:36 25 4
gpt4 key购买 nike

这是 erp.orders:

userId  paidAt
1 2017-06-30
1 2017-06-18
2 2017-06-07
4 2017-06-07
3 2017-01-01
2 2017-01-01
2 2017-01-01
2 2017-01-01

这是 prod.referral_order_delivered

user_id
1
2

这个请求:

select distinct erp.orders."userId", count(erp.orders."userId")
from erp.orders
inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
erp.orders."paidAt"::date >= '2017-06-07'
and erp.orders."paidAt"::date <= '2017-07-07'
group by erp.orders."userId"

会给我这个结果:

userId  count
1 2
2 1

这不是我想要的结果。在 2017-06-07 和 2017-07-07 之间支付的并且在表 prod.referral_order_delivered 中的 id 中,我想计算它们在表 erp.orders 中出现的次数总共。在我当前的请求中,我只计算从 2017-06-07 到 2017-07-07。

我想要的结果是:

userId  count
1 2
2 4

查看如何排除 userId 3 和 4。这真的很重要。你能修改我的请求吗?

最佳答案

尝试拆分您的问题。你想要:

the ids that paid between 2017-06-07 and 2017-07-07 and that are in the table prod.referral_order_delivered

to count how many times they appear in the table erp.orders IN TOTAL

你已经有了前者:

select distinct erp.orders."userId"
from erp.orders inner join prod.referral_order_delivered
on erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
where
erp.orders."paidAt"::date >= '2017-06-07'
and erp.orders."paidAt"::date <= '2017-07-07'

而后者只是简单地使用了一个内部选择:

select erp.orders."userId", count(erp.orders."userId")
from erp.orders
where
erp.orders."userId" in (select ...)
group by erp.orders."userId"

关于sql - 选择计数、内部连接和 where 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44986697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com