這裏是FOR XML路徑的級聯方法:
CREATE TABLE TableA (ID INT, TypeCol CHAR(5));
INSERT INTO TableA (ID,TypeCol) VALUES (12,'Type1')
,(12,'Type2')
,(12,'Type4')
,(13,'Type1')
,(13,'Type2')
,(13,'Type3')
,(14,'Type1')
,(15,'Type6')
,(15,'Type7')
,(15,'Type8')
;WITH cteRequiredTypes AS (
SELECT 'type1' as TypeCol
UNION ALL
SELECT 'type2'
UNION ALL
SELECT 'type3'
)
, cteTableAIds AS (
SELECT DISTINCT Id
FROM
TableA
)
, cteMissingTypes AS (
SELECT
i.ID
,r.TypeCol
FROm
cteRequiredTypes r
CROSS JOIN cteTableAIds i
LEFT JOIN TableA a
ON r.TypeCol = a.TypeCol
AND i.ID = a.ID
WHERE
a.ID IS NULL
)
SELECT
DISTINCT a.ID
,STUFF(
(SELECT ',' + TypeCol
FROM
cteMissingTypes t
WHERE t.ID = a.ID
FOR XML PATH(''))
,1,1,'')
FROM
cteMissingTypes a
相信對於檢查大型數據集有條件的聚集查詢將可能是更好的性能。
條件聚合
SELECT
ID
,CASE WHEN SUM(IIF(TypeCol = 'type1',1,0)) = 0 THEN 'type1' ELSE '' END as Type1
,CASE WHEN SUM(IIF(TypeCol = 'type2',1,0)) = 0 THEN 'type2' ELSE '' END as Type2
,CASE WHEN SUM(IIF(TypeCol = 'type3',1,0)) = 0 THEN 'type3' ELSE '' END as Type3
,STUFF(
REPLACE (
REPLACE (
+ ',' + CASE WHEN SUM(IIF(TypeCol = 'type1',1,0)) = 0 THEN 'type1' ELSE '' END
+ ',' + CASE WHEN SUM(IIF(TypeCol = 'type2',1,0)) = 0 THEN 'type2' ELSE '' END
+ ',' + CASE WHEN SUM(IIF(TypeCol = 'type3',1,0)) = 0 THEN 'type3' ELSE '' END
,',,,',',,')
,',,',',')
,1,1,'') as MissingTypeList
FROM
TableA
GROUP BY
ID
HAVING
SUM(IIF(TypeCol = 'type1',1,0)) = 0
OR SUM(IIF(TypeCol = 'type2',1,0)) = 0
OR SUM(IIF(TypeCol = 'type3',1,0)) = 0
'然後從表A組*具有ID COUNT(*)<3' –
謝謝你的評論,馬克。用戶可能有3種不需要的類型。我會更新我的問題,使其更加精確。 ;) –
你標記了mysql和sql-server,但是你提到你用sql-server 2012做了這個,但是這是哪個呢?你是否在mysql或sql-server這樣做了這個行來連接字符串是非常不一樣的! – Matt