SELECT sq.type, sq.cust, MAX(sq.sum)
FROM (
SELECT C.custid AS cust, P.ptype AS type, SUM(D.qty) AS sum
FROM Customers C, Orders O, Details D, Products P
WHERE C.custid = O.ocust and D.ordid = O.ordid and P.pcode = D.pcode
GROUP BY cust, type
) as sq
GROUP BY sq.type
;
朋友们好,
我的问题是我希望能够通过SQL中的group by函数选择sq.cust和sq.type。使用MAX aggregate时,它无论如何应该只返回1个元组,其中包括sq.type和sq.cust,所以为什么我不能这样访问它?有没有方法返回该产品类型(sq.type)的最大sq.sum的客户id(sq.cust)?
谢谢您!
最佳答案
不要在FROM
子句中使用逗号。始终使用正确、明确、标准的JOIN
语法。
也就是说,你可以在Postgres中使用distinct on
:
SELECT DISTINCT ON (ptype) C.custid as cust, P.ptype AS type, SUM(D.qty) AS sum
FROM Customers C JOIN
Orders O
ON C.custid = O.ocust JOIN
Details D
ON D.ordid = O.ordid JOIN
Products P
ON P.pcode = D.pcode
GROUP BY cust, ptype
ORDER BY ptype, SUM(d.QTY) DESC
关于sql - 在SQL中将GROUP BY与MAX聚合一起使用,并在GROUP BY语句中未选择的其他列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55174834/