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聚合时,无论如何它仅应返回1个元组,其中包括sq.type和sq.cust,那么为什么我无法通过这种方式访问它?有什么方法可以返回该产品类型(sq.type)的最大平方和的客户ID(sq.cust)?
谢谢!
答案 0 :(得分:1)
从不在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
答案 1 :(得分:1)
尽管Pg特定,但Gordon Linoff的解决方案很棒。 为了使其更易于移植,可以使用窗口功能,该功能现在在大多数主要的RDBMS中都可用。
例如,在SQL Server中:
select C.custid as cust, P.ptype, sum(qty) as sum_qty
, FIRST_VALUE(sum(qty)) OVER (PARTITION BY ptype ORDER BY SUM(qty) DESC) as max_sum_qty_for_ptype
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(QTY) DESC
很明显,您可以删除Sum_qty
列