我有一张表Retail
CustomerID Itemset
1 31
1 30
1 78
2 31
2 91
3 30
3 31
我想找到同时CustomerID
和30
的{{1}}的计数。 31
中的Itemset
。
即在这种情况下1
& 3
,因此计数为2
。
我尝试使用&
运算符制定查询,但查询并未返回正确答案。
我的查询 - Select count(customerID) from Retail where Itemset=30 & 31
答案 0 :(得分:3)
select count(*)
from
(
select CustomerId
from Retail
where Itemset in (30,31)
group by CustomerId
having count(distinct Itemset) = 2 -- this guarantees that CustomerId have at least one 30 and at least one 31 in column Itemset
) T
答案 1 :(得分:2)
Select count(distinct(CustomerID)) from (
select r30.CustomerID
from Retail r30
inner join Retail r31 on
r31.CustomerID = r30.CustomerID
where
r30.Itemset = 30
and r31.Itemset = 31
) T
答案 2 :(得分:0)
你只想计算不同的CustomerID ......我没有测试过这个,但是相信这是要走的路......
Select count( distinct customerID)
from Retail
where Itemset in (30,31)
---这是错的......经过一点点的修补,我来到了已经提供的解决方案......请不要理会......
Select count(*)
from (
Select CustomerID
from Retail
where Itemset in (30,31)
group by CustomerID
having count(CustomerID = 2)
) T
---荣誉。这假设CustomerID和Itemset不能有重复项。换句话说,它假定您不会有两行或更多行,而CustomerID和Itemset为1,30。
答案 3 :(得分:0)
试试这个..
select CustomerID,count(*) from [dbo].[Retail] where Itemset in(30,31)
group by CustomerID
如果您只想要计数结果,请使用Common Table Expression
像这样:;with cte1
as
(select CustomerID,count(*) as rs from [dbo].[Retail] where Itemset in(30,31)
group by CustomerID
)
select rs from cte1