我有一份公司,部门和合同的清单。
Company Division Contracts
------- -------- ---------
ABC Avril 0000111
ABC Blocky 0000247
DEF Blocky 0000346
GHI Franklin 0000123
GHI Franklin 0000156
JKL Owned 0000458
JKL Owned 0000567
MNO Owned 0000672
MNO Owned 0000672
我正在尝试这样做,以便我的查询将返回任何与其关联的合同超过1的行,并且这些行也属于同一公司。
上面的案例应该只返回
Company Division Contracts
------- -------- ---------
GHI Franklin 0000123
GHI Franklin 0000156
JKL Owned 0000458
JKL Owned 0000567
在下面的查询中是否可以使用" DISTINCT(concat(division,contracts)))> 1"在下一个查询中,而不是" division",或者我是否完全错了。
SELECT DISTINCT company, division, contracts
FROM inventory
WHERE contracts in (
SELECT DISTINCT contracts
FROM inventory
WHERE division in (
SELECT DISTINCT division
FROM inventory
GROUP BY family HAVING
count(DISTINCT(concat(division, contracts))) > 1
)
GROUP BY contracts HAVING
count(DISTINCT(concat(company, division))) > 1
)
ORDER BY division
答案 0 :(得分:0)
借助Window功能Dense_Rank
Declare @YourTable table (Company varchar(50),Division varchar(50),Contracts varchar(25))
Insert Into @YourTable values
('ABC','Avril','0000111'),
('ABC','Blocky','0000247'),
('DEF','Blocky','0000346'),
('GHI','Franklin','0000123'),
('GHI','Franklin','0000156'),
('JKL','Owned','0000458'),
('JKL','Owned','0000567'),
('MNO','Owned','0000672'),
('MNO','Owned','0000672')
Select A.*
From @YourTable A
Join (Select *,Cnt = Dense_Rank() over (Partition By Company,Division Order By Contracts ) From @YourTable) B
on A.Company=B.Company and A.Division=B.Division and Cnt>1
返回
Company Division Contracts
GHI Franklin 0000123
GHI Franklin 0000156
JKL Owned 0000458
JKL Owned 0000567