答案 0 :(得分:1)
这是一种方法 - 由于请求的值是1,因此总和和计数应该相同:
SELECT Jil_Equipment_ID,
FROM TableName
GROUP BY Jil_Equipment_ID
HAVING SUM(ISNULL(Req_Rule_Id, 1)) = COUNT(ISNULL(Req_Rule_Id, 1))
答案 1 :(得分:1)
你可以在子查询中执行此操作,基本上创建一个子查询,其中包含所有包含NULL或1以外的数据的Jil_Equipment_Id,然后排除这些;
示例数据
CREATE TABLE #TestData (Jil_Equipment_Id int, Req_Rule_id int)
INSERT INTO #TestData
VALUES
(90025,NULL)
,(90025,1)
,(100295,NULL)
,(100295,2)
,(100295,3)
,(3265569,NULL)
,(3265569,1)
,(3265569,2)
,(3265569,9)
,(4091637,NULL)
,(4091637,1)
,(4091637,3)
,(6106396,NULL)
,(6106396,1)
,(6106396,1)
,(6106396,1)
实际查询;
SELECT DISTINCT
a.Jil_Equipment_Id
FROM #TestData a
LEFT JOIN (
SELECT DISTINCT
Jil_Equipment_Id
FROM #TestData
WHERE Req_Rule_id <> 1
AND Req_Rule_id IS NOT NULL
) b
ON a.Jil_Equipment_Id = b.Jil_Equipment_Id
WHERE b.Jil_Equipment_Id IS NULL
结果;
Jil_Equipment_Id
90025
6106396
根据数据的大小,您可能需要查看NOT EXISTS运算符。我保持这样,因为它对更广泛的用户来说更具可读性。
答案 2 :(得分:1)
这将是您对SQL的要求的(几乎)字面翻译:
SELECT Jil_Equipment_ID /* I want to pull Jil_Equipment_ID */
FROM MyTable
WHERE Req_Rule_ID = 1 /* which contains only 1. */
AND NOT EXISTS (
SELECT 1
FROM MyTable AS t2 /* If it contains anything */
WHERE MyTable.Jil_Equipment_ID /* apart from 1 in a group, */
= t2.Jil_Equipment_ID /* it should be neglected. */
AND Req_Rule_ID <> 1
)
它没有针对性能进行优化,但它易于理解,因此可以验证其正确性。
答案 3 :(得分:1)
如果每组只有一个不同的值,则min和max必须是相同的值
SELECT Jil_Equipment_ID
FROM TableName
GROUP BY Jil_Equipment_ID
HAVING MAX(Req_Rule_Id) = 1
AND MIN(Req_Rule_Id) = 1
另一种方法是包括一个与最小值或最大值不同的计数。
SELECT Jil_Equipment_ID
FROM TableName
GROUP BY Jil_Equipment_ID
HAVING MAX(Req_Rule_Id) = 1
AND COUNT (DISTINCT Req_Rule_Id) = 1