我有两张这样的表: -
表A
ITEM LOCATION CODE
A WHS QW123
B WHS QW124
C WHS QW125
表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
使用SQL shold的预期结果如下所示: -
结果
ITEM LOCATION CODE SIZE GRADE
A WHS QW123 26 1
B WHS QW124 20 3
C WHS QW125 27 1
我怎样才能做到这一点?
答案 0 :(得分:1)
获取每件商品的最新ATR_NO,将其与表b连接两次以获得尺寸和等级:
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