开发者

How to extract latest record

开发者 https://www.devze.com 2023-03-05 12:38 出处:网络
I have two tables like this:- TABLE A ITEMLOCATIONCODE AWHSQW123 BWHSQW124 CWHSQW125 TABLE B ATR_NOITEMCODEATT_IDATT_VALUE

I have two tables like this:-

TABLE A

ITEM    LOCATION    CODE
A       WHS         QW123
B       WHS         QW124
C       WHS         QW125

TABLE B

ATR_NO          ITEM    CODE    ATT_ID  ATT_VALUE
20110101123310  A   QW123   SIZE    24
20110101123310  A   QW123   GRADE   2
20110101123351  B   QW124   SIZE    20
20110101123351  B   QW124   GRADE   3
20110101124042  C   QW125   SIZE    26
20110101124042  C   QW125   GRADE   4
20110101131210  A   QW123   SIZE    26
20110101131210  A   QW123   GRADE   1
20110101144542  C   QW125   SIZE    27
20110101144542  C   QW125   GRADE   1

The expected results using SQL s开发者_C百科hold look like this:-

RESULT

ITEM    LOCATION    CODE    SIZE    GRADE
A       WHS         QW123   26  1
B       WHS         QW124   20  3
C       WHS         QW125   27  1

How can I achieve that ?


Get the latest ATR_NO for each item, join that with table b twice to get the size and grade:

select
  a.ITEM, a.LOCATION, a.CODE, SIZE = b1.ATT_VALUE, GRADE = b2.ATT_VALUE
from
  [TABLE A] a
  inner join (select max(ATR_NO) from [TABLE B] group by ITEM) i on i.ITEM = a.ITEM
  inner join [TABLE B] b1 on b1.ATR_NO = i.ATR_NO and b1.ATT_ID = 'SIZE'
  inner join [TABLE B] b2 on b2.ATR_NO = i.ATR_NO and b2.ATT_ID = 'GRADE'
order by
  a.ITEM
0

精彩评论

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