[英]DB2 SQL SELECT top 1 group with join
I'm connecting to a DB2 database and want to use the Max(PO180M1.POORDT) or the TOP 1 grouping by the PO180M2.PHPPN (PARTNO). 我正在连接到DB2数据库,并且想使用Max(PO180M1.POORDT)或按PO180M2.PHPPN(PARTNO)分组的TOP 1。 How would I do this?
我该怎么做? I think I keep getting close but not getting it to work.
我想我一直都在靠近,但没有开始工作。
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
Almost got it. 差不多了。 With any aggregates,
Max()
, Min()
, Avg()
, Count()
, Sum()
, a GROUP BY
clause is required listing the "level" columns which usually are indicator fields (names, categories, types). 对于任何聚合,
Max()
, Min()
, Avg()
, Count()
, Sum()
,需要GROUP BY
子句列出“级别”列,这些列通常是指标字段(名称,类别,类型)。
Also, you will leave out a level column that you are trying to run an aggregate, here being POORDT
. 另外,您将省略尝试运行聚合的级别列,此处为
POORDT
。 Finally, you will not be able to ORDER BY
the very aggregated field but only the group fields listed. 最后,您将无法对非常汇总的字段进行
ORDER BY
,而只能对列出的组字段进行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
By the way, I noticed you used the older syntax of table joins listing tables in FROM
clause with a WHERE
clause. 顺便说一句,我注意到您使用了
FROM
子句中带有WHERE
子句的表联接的较早语法。 I changed it to an INNER JOIN
with ON
which I believe is compliant with DB2. 我将其更改为
ON
的INNER JOIN
,我认为它符合DB2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.