我在DB2中有以下查询但是没有工作,问题是max函数但是我不确定如何解决它。
SELECT CAR.VI max(CAR.ID),
TU.SOLD
FROM P.CAR CAR, A.TU TU WHERE CAR.VI = TU.VI
'Table1' ' VI: USER: DATE: DATE2: STATUS: ID'
' 2T1BU4 DEALER 2012-10-15 2012-10-15 CER 1 '
' 2T1BU4 DEALER 2012-10-15 2012-10-15 CER 2 '
' 2T1BU3 DEALER 2012-10-15 2012-10-15 DRA 1 '
' VI: SOLD:'
' 2T1BU4 Y'
' 2T1BU3 N'
我希望从查询中收到的内容如下:
' VI: USER: DATE: DATE2: STATUS: ID SOLD'
' 2T1BU4 DEALER 2012-10-15 2012-10-15 CER 2 Y '
' 2T1BU3 DEALER 2012-10-15 2012-10-15 DRA 1 N '
我想获得具有最大ID
的VI答案 0 :(得分:2)
你没有提供很多细节,但我猜你想要这个:
SELECT CAR.VI, max(CAR.ID), TU.SOLD
FROM P.CAR CAR
INNER JOIN A.TU TU
ON CAR.VI = TU.VI
GROUP BY CAR.VI, TU.SOLD
或者您可以使用子查询:
select c1.vi, c1.id, tu.sold
from
(
select max(id) id, vi
from P.CAR
group by vi
) c1
inner join A.TU TU
on c1.VI = TU.VI
答案 1 :(得分:0)
使用公用表表达式的变体:
with cte (vi, id) as
(SELECT vi, max(ID)
FROM P.CAR
group by vi)
select cte.vi, cte.id, tu.sold
from cte INNER JOIN A.TU TU
ON cte.VI = TU.VI
答案 2 :(得分:0)
我不是100%确定你想要什么,但听起来你想要每个VI都有MAX(ID)的记录。你需要做这样的事情:
SELECT C1.VI, C1.ID, TU.SOLD FROM P.CAR CAR C1, A.TU TU WHERE C1.VI = TU.VI
WHERE C1.ID = (SELECT MAX(C2.VI) FROM P.CAR C2 WHERE C1.VI = C2.VI)