我正在连接到DB2数据库,并希望使用PO180M2.PHPPN(PARTNO)的Max(PO180M1.POORDT)或TOP 1分组。我该怎么做?我想我一直在接近但没有让它发挥作用。
SELECT PO180M2.PHPPN AS PartNo, (PO180M2.PHVNPD || ' ' || PO180M2.PHVNP2) AS PartDesc,
PO180M1.POORDT AS OrderDate, PO180M2.PHUNCT AS UnitCost
FROM PO180M1, PO180M2
WHERE PO180M1.POORNO = PO180M2.PHORNO
ORDER BY PartNo, OrderDate DESC
答案 0 :(得分:1)
几乎得到了它。对于任何汇总,Max()
,Min()
,Avg()
,Count()
,Sum()
,需要GROUP BY
子句列出“级别”列通常是指标字段(名称,类别,类型)。
此外,您将省略一个您尝试运行聚合的级别列,此处为POORDT
。最后,您将无法ORDER BY
聚合的字段,只能列出列出的组字段。
SELECT PO180M2.PHPPN AS PartNo, (PO180M2.PHVNPD || ' ' || PO180M2.PHVNP2) AS PartDesc,
PO180M2.PHUNCT AS UnitCost, Max(PO180M1.POORDT) As MaxPOORDT
FROM PO180M1
INNER JOIN PO180M2 ON PO180M1.POORNO = PO180M2.PHORNO
GROUP BY PO180M2.PHPPN, (PO180M2.PHVNPD || ' ' || PO180M2.PHVNP2), PO180M2.PHUNCT
ORDER BY PartNo
顺便说一句,我注意到你使用FROM
子句中的表连接列表的旧语法和WHERE
子句。我将其更改为INNER JOIN
ON
我相信它符合DB2。