这是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 IN TOTAL。 根据我目前的要求,我只计算2017-06-07至2017-07-07。
我想要的结果是:
userId count
1 2
2 4
了解如何排除userId 3和4。这非常重要。你可以修改我的请求吗?
答案 0 :(得分:1)
怎么样:
SELECT erp.orders."userId"
,count(erp.orders."paidAt")
FROM erp.orders
INNER JOIN prod.referral_order_delivered
ON erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
AND erp.orders."paidAt"::date >= '2017-06-07'
AND erp.orders."paidAt"::date <= '2017-07-07'
GROUP BY erp.orders."userId"
答案 1 :(得分:1)
使用having
子句而不是where
子句:
select o."userId", count(o."userId")
from erp.orders o inner join
prod.referral_order_delivered rod
on o."userId"::uuid = rod.user_id::uuid
group by o."userId"
having sum( (o."paidAt"::date >= '2017-06-07' and o."paidAt"::date <= '2017-07-07')::int) > 0;
答案 2 :(得分:1)
尝试拆分您的问题。你想要:
2017-06-07和2017-07-07之间支付的ID以及表prod.referral_order_delivered
和
计算它们在表格中显示的次数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"
答案 3 :(得分:1)
当您使用内部联接时,您将在&#34; WHERE&#34;中丢弃您需要的信息。后来的条款。因为它会创建一个时间结果表,您可以在其中省略条目:
where
erp.orders."paidAt"::date >= '2017-06-07'
and erp.orders."paidAt"::date <= '2017-07-07'
所以你需要做的是使用半连接,如下所示:
SELECT DISTINCT erp.orders."userId", COUNT(erp.orders."userId")
FROM erp.orders
WHERE erp.orders."userId" IN (
SELECT erp.orders."userId"
FROM erp.orders, prod.referral_order_delivered
WHERE erp.orders."userId"::uuid = prod.referral_order_delivered.user_id::uuid
AND erp.orders."paidAt"::date >= '2017-06-07'
AND erp.orders."paidAt"::date <= '2017-07-07'
);
GROUP BY erp.orders."userId"
希望它有所帮助!