开发者

SQL Select with Join and last record needed

I've got the following tables:

devices table
SN     tested_d开发者_C百科evice_id  test_setup_id  

129    6      103  
129    7      104   
130    8      106

test_setup table
test_setup_id data1  
103 111  
104 333  
106 555  

I want to deliver SN, test_setup_id, data1 for the last instance of each

serial number as follows:  
129,104,333   
130,106,555  

(Omitting the earlier copy of SN 129).

I have a query as follows which deliver both records for SN 129 and don't know how to condition it to only deliver the last of them:

SELECT sn, 
       test_setup_id, 
       data1 
FROM   test_setup 
       INNER JOIN devices 
         ON test_setup.test_setup_id = devices.test_setup_id 

Any assistance would be welcomed. Thank you.


Try this

SELECT d.sn, 
       d.test_setup_id, 
       ts.data1 
FROM   (SELECT d.sn, 
               MAX(d.test_setup_id) test_setup_id 
        FROM   devices d 
        GROUP  BY d.sn) maxsetupid 
       INNER JOIN devices d 
         ON maxsetupid.test_setup_id = d.test_setup_id 
       INNER JOIN test_setup ts 
         ON d.test_setup_id = ts.test_setup_id 


SELECT
  d.SN, d.test_setup_id, ts.data1
FROM devices d
  LEFT JOIN devices d2 ON d.SN = d2.SN and d.test_setup_id < d2.test_setup_id
  INNER JOIN test_setup ts ON d.test_setup_id = ts.test_setup_id
WHERE d2.SN IS NULL


If the test_setup_id is always incrementing, you can do something like:

SELECT sn, 
       test_setup_id, 
       data1 
FROM   test_setup 
       INNER JOIN devices 
         ON test_setup.test_setup_id = devices.test_setup_id 
WHERE  test_setup_id = (SELECT MAX(test_setup_id) 
                        FROM   test_setup) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜