2017-05-03 45 views
0

我有一個奇怪的TSQL問題應該是非常簡單的,但我無法解決如何糾正它。SQL列表和只列表

讓我們假設我有一個表格ID ID |物品ID

+--------+---------+ 
| Box ID | Item ID | 
+--------+---------+ 
|  1 |  1 | 
|  1 |  2 | 
|  1 |  3 | 
|  2 |  1 | 
|  2 |  2 | 
|  2 |  3 | 
|  2 |  4 | 
|  3 |  1 | 
|  3 |  2 | 
|  3 |  3 | 
|  3 |  4 | 
|  3 |  5 | 
+--------+---------+ 

我有一個項目列表1,2,3,我只想知道只有那些項目的工具包。 Kit 1.很明顯,In會給我包括任何東西。我不知道它的工作是否能夠計算出有多少人進出。

任何想法,不勝感激。

所以我幾乎在那裏感謝大家。我已經擴展到了。

DECLARE @Instances AS TABLE(PlateID INT); 

INSERT INTO @Instances(PlateID)VALUES(11638),(11637),(11632),(11659) 

DECLARE @NumberofPlates INT; 
SELECT @NumberofPlates = COUNT(*) FROM @Instances; 

SELECT Instance_Plate_Room_Instance_ID_LNK 
from dbo.M_Instance_Plate 
WHERE Instance_Plate_Deleted = 0 
group by Instance_Plate_Room_Instance_ID_LNK 
having sum(case when Instance_Plate_Plate_ID_LNK not in (SELECT PlateID FROM 
@Instances) then 1 else 0 end) = 0 and 
    SUM(case when Instance_Plate_Plate_ID_LNK in (SELECT PlateID FROM 
@Instances) then 1 else 0 end) = @NumberofPlates; 

上變圓了不能對包含聚合或子查詢的表達式執行聚合功能的任何提示。在@Instances代碼中選擇PlateID。

+1

GROUP BY,HAVING,COUNT DISTINCT。 – jarlh

回答

1

您可以使用group byhaving

select boxid 
from t 
group by boxid 
having sum(case when itemid not in (1, 2, 3) then 1 else 0 end) = 0 and 
     sum(case when itemid in (1, 2, 3) then 1 else 0 end) = 3; 

注意,第二個條件取決於兩個因素:

  • 是否有重複?如果是這樣,邏輯將不得不稍微改變。
  • 你真的想要所有三個項目?或者僅僅是沒有非1,2,3項目就足夠了?如果是後者,則刪除第二個條件。
0

我只是尋找不同的可能性,你不想在一個集合中,然後消除該集合。像這樣:

DECLARE @Data TABLE (BoxId INT, ItemId Int); 

INSERT INTO @Data VALUES (1, 1), (1, 2),(1, 3),(2, 1),(2, 2),(2, 3),(2, 4),(3, 1),(3, 2),(3, 3),(3, 4),(3, 5) 

--as is 
Select * 
From @Data 

--Look up a set that is what you do not want, seperate it(I just did a nested select in a where clause, you can do a CTE, table variable, whatevs) 
SELECT distinct BoxId 
From @Data 
WHERE BoxId NOT IN (Select BoxId From @Data WHERE ItemId IN (4,5))