我有一张表格如下
TextBlock
如何编写SQL查询以使所有PriceCardId具有Day包含
Id | PriceCardId | Days
1 | 1 | 2
2 | 1 | 4
3 | 1 | 5
4 | 1 | 6
5 | 1 | 3
6 | 2 | 5
7 | 2 | 3
8 | 3 | 6
谢谢!
答案 0 :(得分:3)
我想你想要:
select pricecardid
from t
where day in (2, 4, 5, 6)
group by pricecardid
having count(*) = 4; -- the number of days you are looking for
这假设您的表中没有重复项。如果存在重复项,请使用having count(distinct day)
代替count(*)
。
注意:您可以将其标记为:
with d as (
select v.dy
from values ( (2), (4), (5), (6) ) v(dy)
)
select pricecardid
from t
where day in (select d.dy from d)
group by pricecardid
having count(*) = (select count(*) from d);
答案 1 :(得分:1)
试试这个:
SELECT PriceCardId
FROM [My_Table]
WHERE [Day] IN(2,4,5,6)
GROUP BY PriceCardId
HAVING COUNT(DISTINCT [Day])=4