表1
ColumnA - Column B Column C
111 Null AA
111 Null BB
222 Null CC
333 555,222 DD
444 Null EE
666 777 FF
888 777 GG
我需要打印所有行
其中A列中的数字超过两次 A列中的数字与b列中的数字匹配且出现次数不止一次(A列上的第3行与b列的第4行匹配)
预期输出
111 Null AA
111 Null BB
222 Null CC
333 555,222 DD
答案 0 :(得分:1)
要从表中获取不同的记录,您可以在查询中使用带有字段名称
的distinct关键字从Table1中选择不同的ColumnA,B列
答案 1 :(得分:0)
样本表
CREATE TABLE #TEMP(COLUMNA INT,COLUMNB VARCHAR(30),COLUMNC VARCHAR(30))
INSERT INTO #TEMP
SELECT 111, Null, 'AA'
UNION ALL
SELECT 111, Null, 'BB'
UNION ALL
SELECT 222, Null, 'CC'
UNION ALL
SELECT 333, '555,222', 'DD'
UNION ALL
SELECT 444, Null, 'EE'
UNION ALL
SELECT 666, '777', 'FF'
UNION ALL
SELECT 888, '777', 'GG'
<强> QUERY 强>
我在查询中写了逻辑
;WITH CTE AS
(
-- Get the CSV as rows and count the occurance of ColumnA
SELECT COLUMNA,LTRIM(RTRIM(Split.a.value('.', 'VARCHAR(100)'))) 'COLUMNB',COLUMNC,
COUNT(COLUMNA) OVER(PARTITION BY COLUMNA) CNT
FROM
(
-- Select the values to convert into rows from CSV
SELECT COLUMNA,
CAST ('<M>' + REPLACE(ISNULL(COLUMNB,''), ',', '</M><M>') + '</M>' AS XML) AS Data,
COLUMNC
FROM #TEMP
) AS A
CROSS APPLY Data.nodes ('/M') AS Split(a)
)
-- Find the rows where number of each unique item in ColumnA > 1
-- and ColumnA element exists in ColumnB
SELECT DISTINCT T.*
FROM CTE C
JOIN #TEMP T ON C.COLUMNA=T.COLUMNA
WHERE CNT > 1
OR C.COLUMNA IN (SELECT DISTINCT COLUMNB FROM CTE)
<强> RESULT 强>
修改强>
如果您想在两个条件都满足时获取记录,请在最后一行使用AND
代替OR
,即
AND C.COLUMNA IN (SELECT DISTINCT COLUMNB FROM CTE)