对于SQL Server,我有一个带
的表CostumerID TITLE DATE
1 m1 1999-05-08
1 m1 2000-07-10
1 m1 2001-12-11
1 m2 2008-03-20
1 m2 2005-09-05
1 m2 2011-07-08
1 m3 2006-07-22
1 m3 2009-01-19
1 m3 2012-02-18
2 m1 2007-09-28
2 m1 2010-11-19
2 m1 2009-08-09
2 m2 2010-04-22
2 m2 2008-10-16
2 m2 2010-07-22
2 m3 2013-07-31
2 m3 2011-01-11
2 m3 2010-02-20
3 m1 2010-04-07
3 m1 2011-06-11
3 m1 2010-11-09
3 m2 2013-08-21
3 m2 2014-07-19
3 m2 2015-12-29
3 m3 2011-04-17
3 m3 2014-01-31
3 m3 2012-09-19
2 m3 2010-02-03
…
问题1:我需要找到1月和2月消费了产品的CostumerID。
Select a.CostumerID
From
(Select distinct CostumerID from theTable where month(date) = '2') as a
Inner join
(Select distinct CostumerID from theTable where month(date) = '1') as b
On a.CostumerID = b.CostumerID
Q2:另外,我需要找到每个客户第一次消费的所有产品中最喜欢的产品。
Select b.title, count(b.title) as cnt
from
(
Select a.CostumerID , min(a.date) as earliestDate
from [DJX_test1].dbo.ama_services as a
group by a.CostumerID
) as c
inner join [DJX_test1].dbo.ama_services as b
on b.CostumerID = c.CostumerID and b.[date] = c.earliestDate
group by b.title
order by cnt desc
表格大小可能很大,有10多万行。 没有使用子查询会有更好的查询吗? 另外,如何在不运行查询的情况下估计查询的性能?
感谢
答案 0 :(得分:0)
对于第一个问题,试试这个:
SELECT DISTINCT costumerID
FROM theTable
WHERE month(date)='1' OR month(date)='2'
答案 1 :(得分:0)
问题1:我需要找到1月和2月消费了产品的CostumerID。
SELECT costumerID
FROM theTable
WHERE month(Convert(date,[date]))='1' OR month(Convert(date,[date]))='2'
Q2:另外,我需要找到每个客户第一次消费的所有产品中最喜欢的产品。
您可以使用如下的dense_rank()函数轻松实现它。
;with cte as
(
select costumerID,title,date,
dense_rank() over (partition by costumerid order by convert(Date,[date])) as rn
from theTable
)
select * from cte where rn=1