我需要以下示例的帮助,这个例子是连接4个表和左外连接的结果,因为我需要检查所有列甚至知道可以获得空值,但我真正想要的是得到1根据c6上的最后一个更高值记录每个C6。
C1 C2 C3 C4 C5 C6
4 A MM 90 GT 798
4 A MM 90 GT 625
4 A MM 90 GT 354
4 A MM 90 GT 547
5 K EE 60 SV 213
5 K EE 60 SV 235
5 K EE 60 SV 236
9 O WW 40 PE 456
9 O WW 40 PE 487
9 O WW 40 PE 982
我正在使用的查询是这样的:
SELECT distinct C1, C2, C3, C4,C5,C6
--,row_number() OVER(partition by c6 ORDER BY c1 asc)
FROM table1 n
left outer join table 2 j on j.cad = n.Cad and j.P = n.P and j.H = 'Name'
left outer join table 3 k on k.id = n.id
left outer join table 4 m on m.u = n.u and m.s = n.s and m.Cad = n.Cad and n.P = m.P
where NOT EXISTS (SELECT 1 from table 5 v WHERE N.U=v.U and N.S=v.S
and N.Cad=v.Cad and N.P=v.P) and n.Cad is not null
and C6 is not null

答案 0 :(得分:1)
尝试使用以下查询。
With cte_1
As( SELECT C1, C2, C3, C4,C5,C6
,row_number() OVER(partition by c1,c2,c3,c4,c5 ORDER BY c6 desc) RNO
FROM table1 n
left outer join table 2 j on j.cad = n.Cad and j.P = n.P and j.H = 'Name'
left outer join table 3 k on k.id = n.id
left outer join table 4 m on m.u = n.u and m.s = n.s and m.Cad = n.Cad and n.P = m.P
where NOT EXISTS (SELECT 1 from table 5 v WHERE N.U=v.U and N.S=v.S
and N.Cad=v.Cad and N.P=v.P) and n.Cad is not null
and C6 is not null)
SELECT C1, C2, C3, C4,C5,C6 FROM cte_1
WHERE RNO=1