gpt4 book ai didi

sql - 选择用户每年购买的地方

转载 作者:行者123 更新时间:2023-12-04 20:39:57 25 4
gpt4 key购买 nike

我有一个 sales 表,其中存储了每笔销售。此表包含 year_ordereduserIdorderId 等列。

我希望编写一个 SQL 查询来选择用户从 2008 年开始每年订购的行。所以我只想要那些从2008年到2014年一直忠诚和订购的人。

我已尝试使用此查询,但它给了我 year_ordered 大于 2007 的任何内容 -

select COUNT(*) as sales_count, ss.userID, ss.year_ordered 
from subscriber_sub ss
where ss.date_deleted is null
and ss.year_ordered > 2007
group by ss.year_ordered, ss.userID
having COUNT(*) > 1
order by ss.year_ordered

最佳答案

你所追求的东西叫做关系划分。基本上有两种方法可以实现:

select COUNT(distinct ss.year_ordered) as sales_count, ss.userID 
from subscriber_sub ss
where ss.date_deleted is null
and ss.year_ordered > 2007
group by ss.userID
having COUNT(distinct ss.year_ordered) >= ( select 2014 - 2008 )

另一种方法是重写 FORALL x : p(x) <=> NOT EXISTS x : NOT p(x),即用户在某年不存在,因此该年没有销售。我会把它作为练习:-)

关于sql - 选择用户每年购买的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25364805/

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