我想加入两个表,其中table1仅包含1条记录,table2包含具有相同ID但序列号不同的多个记录。加入是在wkid上,但我只想从table2中获得最大序列号
SELECT
t1.wkid
, t1.ser
, t2.nama
, t1.comments
FROM
table1 t1
, table2 t2
WHERE
t1.wkid = t2.wkid
AND t2.ser = MAX(ser)
表的创建和插入:
create table table1(wkid int, ser int, comments text);
insert into table1 values(721142, 1, 'asdfasd');
insert into table1 values(721142, 2, 'vnivnie');
insert into table1 values(721142, 3, 'el;eklke');
insert into table1 values(721142, 4, 'fefeo');
insert into table1 values(721142, 5, 'jijie');
insert into table1 values(721143, 1, 'my comments 1');
insert into table1 values(721143, 2, 'my comments 2');
insert into table1 values(721143, 3, 'my comments 3');
create table table2(wkid int, nama text);
insert into table2 values(721142, 'John');
insert into table2 values(721143, 'Andy');
insert into table2 values(721144, 'Khan');
insert into table2 values(721145, 'Jack');
预期结果:
721142 | 5 | John | jijie
721143 | 3 | Andy | my comments 3
答案 0 :(得分:0)
您可以使用row_number()
select * from
(
select t1.wkid, t1.ser, t2.nama, t1.comments, row_number() over(partition by t1.wkid order by ser desc) as rn
from table1 t1 inner join table2 t2 on t1.wkid = t2.wkid
)A where rn=1
输出:
wkid ser nama comments rn
721142 5 John jijie 1
721143 3 Andy my comments 3 1
答案 1 :(得分:0)
隐含加入
SELECT A.wkid, A.ser, B.nama, A.comments
FROM table1 A, table2 B
WHERE B.wkid = A.wkid
AND A.ser = (SELECT max(X.ser) FROM table1 X
WHERE X.wkid = A.wkid)
显式加入
SELECT A.wkid, A.ser, B.nama, A.comments
FROM table1 A JOIN table2 B
ON B.wkid = A.wkid
WHERE A.ser = (SELECT max(X.ser) FROM table1 X
WHERE X.wkid = A.wkid)
答案 2 :(得分:0)
从不在FROM
子句中使用逗号。 始终使用正确的,明确的,标准 JOIN
语法。
在这种情况下,具有讽刺意味的是,最好的解决方案可能使用APPLY
而不是JOIN
:
SELECT t1.wkid, t2.ser, t2.nama, t1.comments
FROM table1 t1 CROSS APPLY
(SELECT TOP (1) t2.*
FROM table2 t2
WHERE t1.wkid = t2.wkid
ORDER BY t2.ser DESC
) t2;
这应该有效地使用table2(wkid, ser desc)
上的索引。