答案 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)