我有一个交易表,其中包含每家公司的项目详细信息。我想写一个查询来检索只有项目编号1,2和3的公司(根据我在下面的示例代码)。选定的公司应该拥有所有1,2,3项。如果某个公司只有第1项,那么就不应该来。我怎么写这个?
bla,bla,bla,bla ok
如何使用CREATE TABLE #TmpTran
(
ID BIGINT IDENTITY,
COMPANY_ID BIGINT,
ITEM_NAME VARCHAR(50),
ITEM_NUMBER INT
)
INSERT INTO #TmpTran (COMPANY_ID, ITEM_NAME, ITEM_NUMBER)
VALUES (1, 'ABC', 1), (1, 'DEF', 2), (1, 'HIJ', 3),
(2, 'KLM', 4), (2, 'KLM', 5), (2, 'ABC', 1)
或WHERE
查询仅获取公司1数据?
答案 0 :(得分:7)
您可以使用group by
和having
:
select company_id
from #tmptran tt
where item_number in (1, 2, 3)
group by company_id
having count(distinct item_number) = 3;
答案 1 :(得分:1)
另一种方式(更灵活的方法)
select company_id
from #tmptran tt
group by company_id
having count(case when item_number = 1 then 1 end) > 0;
and count(case when item_number = 2 then 1 end) > 0;
and count(case when item_number = 3 then 1 end) > 0;
答案 2 :(得分:1)
{{1}}
答案 3 :(得分:0)
你说你有很多领域。读者可能最容易理解的是:
select distinct tt.company_id
from #tmptran tt
where tt.item_number in (1, 2, 3)
and exists(select 1
from #tmptran ttSub
where ttSub.company_id = tt.company_id and ttSub.item_number = 1)
and exists(select 1
from #tmptran ttSub
where ttSub.company_id = tt.company_id and ttSub.item_number = 2)
and exists(select 1
from #tmptran ttSub
where ttSub.company_id = tt.company_id and ttSub.item_number = 3)