我正在尝试加入2个表,但只选择表B中的id,其中id最大,表A和表之间匹配2列。乙
我试过这个,但由于表2的值最高,它只选择1行,但我需要显示整个表A.
WITH CTE AS
(
SELECT DocNum, Status
FROM TableB
WHERE Id = (SELECT MAX(Id) FROM TableB)
)
SELECT TableA.DocNum, DocTitle, cte.Status
FROM TableA
INNER JOIN cte
ON TableA.DocNum = cte.DocNum
以下示例:
Table A
Id DocNum DocTitle
1 ST-0001 SomeTitle
2 ST-0002 SomeTitle
3 ST-0003 SomeTitle
4 ST-0004 SomeTitle
5 ST-0005 SomeTitle
Table B
Id DocNum Status
1 ST-0001 Incomplete
2 ST-0001 Complete
3 ST-0002 Complete
4 ST-0003 Incomplete
5 ST-0004 Incomplete
6 ST-0004 Complete
7 ST-0005 Incomplete
Result
DocNum DocTitle Status
ST-0001 SomeTitle Complete
ST-0002 SomeTitle Complete
ST-0003 SomeTitle Incomplete
ST-0004 SomeTitle Complete
ST-0005 SomeTitle Incomplete
答案 0 :(得分:0)
您可以使用带有Row_number的CTE来获取tableB中每个docNum的最大ID的行,然后加入到该cte。
首先,创建并填充样本表(请在将来的问题中保存此步骤):
DECLARE @A As Table
(
Id int,
DocNum char(7),
DocTitle varchar(20)
);
DECLARE @B As Table
(
Id int,
DocNum char(7),
[Status] varchar(20)
);
INSERT INTO @A VALUES
(1, 'ST-0001', 'SomeTitle'),
(2, 'ST-0002', 'SomeTitle'),
(3, 'ST-0003', 'SomeTitle'),
(4, 'ST-0004', 'SomeTitle'),
(5, 'ST-0005', 'SomeTitle');
INSERT INTO @B VALUES
(1, 'ST-0001', 'Incomplete'),
(2, 'ST-0001', 'Complete'),
(3, 'ST-0002', 'Complete'),
(4, 'ST-0003', 'Incomplete'),
(5, 'ST-0004', 'Incomplete'),
(6, 'ST-0004', 'Complete'),
(7, 'ST-0005', 'Incomplete');
然后,使用tableB中的row_number创建cte:
;WITH CTE AS
(
SELECT Id,
DocNum,
[Status],
ROW_NUMBER() OVER(PARTITION BY DocNum ORDER BY Id DESC) As Rn
FROM @B
)
查询:
SELECT A.DocNum, A.DocTitle, CTE.[Status]
FROM @A A
INNER JOIN CTE ON A.DocNum = CTE.DocNum
WHERE CTE.rn = 1
结果:
DocNum DocTitle Status
ST-0001 SomeTitle Complete
ST-0002 SomeTitle Complete
ST-0003 SomeTitle Incomplete
ST-0004 SomeTitle Complete
ST-0005 SomeTitle Incomplete