我写了请求,但恐怕它可能没有经过优化,所以会遇到问题。
任务:查找没有债务且上一次付款超过2年的用户。没有订单的不必要的用户
我们有两个表:
User tbl (Id (int), LastName (string))
Order tbl (Id (int), UserId (int), IsPaid (bool), DatePaid (Date, not null))
我写了一个Sql请求,但恐怕我的用户数和订单数都下降了20k
我发现所有没有债务的人,最后一次还款期为两年。 现在,我想将它们从常规列表中删除,这样需要我的用户就可以保留。 好主意
SELECT u."Id"
FROM "User" AS u
LEFT JOIN
(SELECT *
FROM "Order"
WHERE "UserId" IN
(SELECT "Id"
FROM "User"
WHERE "Id" NOT IN
(SELECT DISTINCT "UserId"
FROM "Order"
WHERE "IsPaid" IS FALSE )
)
AND "DatePaid" > '2016-10-10'
) AS p
ON p."UserId" = u."Id";
答案 0 :(得分:2)
我认为您只是想要这样的东西:
select o.userid
from orders o
group by o.userid
having sum(case when o.isPaid then 1 else 0 end) = count(*) and -- all are paid
max(o.paymentdate) < current_date - interval '2 year';
请注意,日期函数众所周知是特定于数据库的。上面使用ANSI / ISO标准语法。
如果要获取有关用户的完整信息,则可以使用其他结构:
select u.*
from users u
where not exists (select 1
from orders o
where o.userid = u.id and not u.ispaid
) and
not exists (select 1
from orders o
where o.userid = u.id and
u.paymentdate > current_date - interval '2 year'
);