我试图根据同一个表中的另一行修改一个列值,所以我使用自联接,我得到了预期的更改,但它选择了两行(原始行和修改后的行),我不'不想选择原始行,如果其任何列被修改,则应仅选择修改的行,如果其值被修改,则应选择原始行。我创建了一个类似的架构来详细说明该问题:
create table tbl
(
id int not null,
status int not null,
name varchar null,
subject varchar null,
result varchar null
);
/* Create few records in this table */
INSERT INTO tbl VALUES(1, 1, 'A', 'sub1', 'Pending');
INSERT INTO tbl VALUES(2, 2, 'A', 'all', 'Passed');
INSERT INTO tbl VALUES(3, 1, 'B', 'sub1', 'Pending');
INSERT INTO tbl VALUES(4, 3, 'B', 'sub2', 'Failed');
INSERT INTO tbl VALUES(5, 3, 'C', 'sub1', 'Failed');
INSERT INTO tbl VALUES(6, 2, 'D', 'sub1', 'Passed');
INSERT INTO tbl VALUES(7, 1, 'E', 'sub1', 'Pending');
COMMIT;
SELECT distinct t1.id, t1.status, t1.name, t1.subject,
CASE
WHEN t1.status = 1 and t2.subject = 'all' and t2.status = 2 THEN 'Passed'
WHEN t1.status = 1 THEN 'Pending'
WHEN t1.status = 2 THEN 'Passed'
WHEN t1.status = 3 THEN 'Failed'
END AS 'result'
FROM tbl t1 join tbl t2 on t1.name = t2.name
-----结果----------------------------
1|1|A|sub1|Pending
1|1|A|sub1|Passed
2|2|A|all|Passed
3|1|B|sub1|Pending
4|3|B|sub2|Failed
5|3|C|sub1|Failed
6|2|D|sub1|Passed
7|1|E|sub1|Pending
此处,ID: 1
的行出现重复,我不再需要第一行,因为我将其 Result
列值修改为 Passed
基于原始表中的第二行主题:全部(ID:2)
。
------预期结果------------------------
1|1|A|sub1|Passed
2|2|A|all|Passed
3|1|B|sub1|Pending
4|3|B|sub2|Failed
5|3|C|sub1|Failed
6|2|D|sub1|Passed
7|1|E|sub1|Pending
最佳答案
您的示例的问题是您的联接生成一行,其中两侧都有 subject = sub1
,因此您的 CASE 语句无法捕获它。修改查询以获得所需结果的最简单方法是通过扩展联接条件以排除类似状态来消除这种情况。
SELECT distinct t1.id, t1.status, t1.name, t1.subject,
CASE
WHEN t1.status = 1 and t2.subject = 'all' and t2.status = 2 THEN 'Passed'
WHEN t1.status = 1 THEN 'Pending'
WHEN t1.status = 2 THEN 'Passed'
WHEN t1.status = 3 THEN 'Failed'
END AS 'result'
FROM tbl t1 left join tbl t2 on t1.name = t2.name AND t1.status <> t2.status
关于sql - 如何删除SQL Server自连接中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58860698/