我正在使用SQL Server 2012并且已经完成了研究,但找不到我的答案,因为我不知道如何在谷歌上正确地说出来,或者在搜索栏中找到我需要的答案。
我使用3列X,Y,Z处理数据。 我想写一个查询,告诉我:
我需要过滤它,我绝对感到困惑。
我尝试了GROUP BY
选项,但其中一个列不是可以“按分组”的数据
我试过SELECT DISTINCT
但也没有运气。
答案 0 :(得分:0)
select X, Y, count(distinct Z)
from table
group by X, Y
having count(distinct Z) > 1
答案 1 :(得分:0)
这真的很难看,但似乎有效。包含一些示例数据以验证结果。存在一个更优雅的解决方案,但是这个解决方案很有效。
DECLARE @T TABLE (X VARCHAR(5),Y VARCHAR(5),Z VARCHAR(5),NOTES VARCHAR(50))
INSERT INTO @T VALUES
('A','01','D','DUPE X|'),('B','02','',''),('C','03','',''),('D','04','',''),
('E','05','',''),('F','06','',''),('G','07','',''),('H','08','',''),
('A','09','Z1','DUPE X| DUPE 09| UNIQ Z1' ),('A','09','D','DUPE X| DUPE 09| UNIQ D'),
('A','10','D','DUPE X|'),('A','09','Z2','DUPE X| DUPE 09| UNIQ Z2'),('K','13','',''),
('L','14','',''),('M','15','',''),('A','09','D1','DUPE X| DUPE 09 | DUPE D1'),
('A','09','D1','DUPE X| DUPE 09 | DUPE D1')
SELECT
T.X, T.Y , T.Z
FROM
@T AS T
INNER JOIN
(SELECT distinct X,Y,COUNT(*) AS XY FROM @T GROUP BY X,Y HAVING COUNT(*) > 1) AS L ON T.X = L.X AND T.Y = L.Y
INNER JOIN
(SELECT distinct X,Y,Z,COUNT(*) AS XYZ FROM @T GROUP BY X,Y,Z HAVING COUNT(*) = 1 ) AS U ON T.X = U.X AND T.Y = U.Y AND T.Z = U.Z