各位老手,請問我有一個表格,想要讓他條件一樣的合併,不知道要如何做到呢
SQL Server 2019
ID欄,要把後面的多餘的字元去掉,然後再
ID跟NO跟DIA條件相同讓他合併再一起
最終 YN欄 有N的就顯示N沒有N就顯示Y像這樣
CREATE TABLE TableX
(ID varchar(20),
NO varchar(20),
DIA varchar(20),
YN varchar(20)
);
INSERT INTO TableX
VALUES
('3201-20210103001','1','A','y'),
('3201-20210103001','2','A','y'),
('3201-20210103001_002','1','A','n'),
('3201-20210103001_001','2','B','n'),
('3201-210104001','1','A','n'),
('3201-210104001-ati','1','A','n'),
('3201-210104001_01','1','A','n'),
('3201-210104001_02','2','B','n');
SELECT ID,NO,DIA,
CASE WHEN SUM(CASE WHEN YN='y' THEN 0 ELSE 1 END)=0 THEN 'y' ELSE 'n' END AS YN
FROM (
SELECT
d.vals.value('(/TR/TD)[1]','VARCHAR(20)') +'-'+
d.vals.value('(/TR/TD)[2]','VARCHAR(20)') 'ID',
NO,DIA,YN
FROM (
SELECT CAST('<TR><TD>' + REPLACE(REPLACE(ID,'_','-'), '-', '</TD><TD>') + '</TD></TR>' AS xml) vals,
NO,DIA,YN
FROM TableX) AS d
) AS M
GROUP BY ID,NO,DIA