SQL服务器查询以查找表中的重复,其中行中显示“是”/“否”

时间:2018-01-31 06:21:20

标签: sql-server sql-server-2008 sql-server-2008-r2

我想找到重复的记录,并在结果表格中以行到列的格式显示它,其中包含Y / N值。

附件是我期望的样本表和结果表结果。 enter image description here

谢谢, Kavin

2 个答案:

答案 0 :(得分:0)

请使用PIVOT尝试此解决方案。

数据生成

CREATE TABLE Table1
(
     Name VARCHAR(10)
    ,SNO INT
    ,DNO VARCHAR(10)
)
GO

INSERT INTO Table1 VALUES
('qwe',123, 'd1'),
('qwe',123, 'd2'),
('qwe',123, 'd3'),
('qwe',123, 'd4'),
('asd',456, 'd4'),
('asd',456, 'd4')
GO

<强>解

;WITH CTE AS
(
    SELECT * , 'Y' N, COUNT(*) OVER(PARTITION BY name,sno) cnt FROM Table1
)
,CTE1 AS
(
    SELECT Name,SNO,
    ISNULL([d1],'N') [d1],ISNULL([d2],'N') [d2],ISNULL([d3],'N') [d3],ISNULL([d4],'N') [d4]     
    FROM CTE
    PIVOT
    (
        MAX(N) FOR DNO IN ([d1],[d2],[d3],[d4])
    )t
)
SELECT * , 
         CASE WHEN [d1] = 'Y' THEN 1 ELSE 0 END + 
         CASE WHEN [d2] = 'Y' THEN 1 ELSE 0 END + 
         CASE WHEN [d3] = 'Y' THEN 1 ELSE 0 END + 
         CASE WHEN [d4] = 'Y' THEN 1 ELSE 0 END Cnt
FROM CTE1

<强>输出

Name       SNO         d1   d2   d3   d4   Cnt
---------- ----------- ---- ---- ---- ---- -----------
qwe        123         Y    Y    Y    Y    4
asd        456         N    N    N    Y    1

(2 rows affected)

答案 1 :(得分:0)

没有阴茎的另一种解决方案。。有点容易理解,因为许多人发现枢轴有点难以吸收。

SELECT * , 
         CASE WHEN [d1] = 'Y' THEN 1 ELSE 0 END + 
         CASE WHEN [d2] = 'Y' THEN 1 ELSE 0 END + 
         CASE WHEN [d3] = 'Y' THEN 1 ELSE 0 END + 
         CASE WHEN [d4] = 'Y' THEN 1 ELSE 0 END Cnt
FROM 
(
    SELECT Name,SNO
        ,MAX(CASE WHEN DNO = 'd1' THEN 'Y' ELSE 'N' END) [d1] 
        ,MAX(CASE WHEN DNO = 'd2' THEN 'Y' ELSE 'N' END) [d2]
        ,MAX(CASE WHEN DNO = 'd3' THEN 'Y' ELSE 'N' END) [d3]
        ,MAX(CASE WHEN DNO = 'd4' THEN 'Y' ELSE 'N' END) [d4]    
    FROM Table1
    GROUP BY Name,SNO
)y

<强>输出

Name       SNO         d1   d2   d3   d4   Cnt
---------- ----------- ---- ---- ---- ---- -----------
qwe        123         Y    Y    Y    Y    4
asd        456         N    N    N    Y    1

(2 rows affected)