我需要一个查询来查找没有获得“评级6”记录的检查/组件。我将插入新记录,以便所有检查/组件都有“评级6”记录以及他们可能拥有的其他评级。
请考虑以下数据:57646,57652和57657 不正确,因为他们缺少评级6记录。在此数据示例中,这三个应该是查询返回的唯一检查/组件。
InspectionID ComponentID RatingTypeID
138 57646 10
138 57647 6
138 57647 2
138 57648 6
138 57649 6
138 57650 6
138 57651 10
138 57651 6
138 57652 10
138 57653 6
138 57654 6
138 57655 6
138 57656 6
138 57657 10
答案 0 :(得分:4)
SELECT *
FROM YourTable A
WHERE NOT EXISTS(SELECT 1 FROM YourTable
WHERE InspectionID = A.InspectionID
AND ComponentID = A.ComponentID
AND RatingTypeID = 6)
答案 1 :(得分:2)
SELECT A.InspectionID FROM MyTable AS A
LEFT OUTER JOIN MyTable AS B
ON A.InspectionID = B.InspectionID AND B.RatingTypeID = 6
WHERE B.InspectionID IS NULL
答案 2 :(得分:1)
这应该只需一次就能完成。
SELECT src.*
FROM
(
SELECT x.InspectionID,
x.ComponentID,
MAX(CASE WHEN x.RatingTypeID = 6 THEN 1 ELSE 0 END) AS HasRatingTypeID6
FROM dbo.MyTable x
GROUP BY x.InspectionID, x.ComponentID
) src
WHERE src.HasRatingTypeID6 = 1
答案 3 :(得分:0)
select * from YOURTABLE where componentId not in (select componentId from YOURTABLE where RatingTypeId=6)