简体   繁体   中英

in sql how to get the max of sum that is group by two columns

SELECT county, category_name, SUM(bottle_qty*(btl_price-state_btl_cost)) AS profit
FROM sales
GROUP BY county, category_name
ORDER BY profit DESC

I want profit for each county and what category_name is produces the most profit in that county.

So I just want the first row, 8th row and 11th row:

所以我只想要第一行,第8行和第11行

You can use distinct on to solve this greatest-n-per-group problem:

SELECT DISTINCT ON(county)
    county, 
    category_name,
    SUM(bottle_qty*(btl_price-state_btl_cost)) AS profit 
FROM sales 
GROUP BY county, category_name 
ORDER BY county, profit DESC

However this does not let you control the ordering of the rows in the resultset. In that case, use row_number() instead:

SELECT *
FROM (
    SELECT
        county, 
        category_name,
        SUM(bottle_qty*(btl_price-state_btl_cost)) AS profit 
        ROW_NUMBER() OVER(
            PARTITION BY county 
            ORDER BY SUM(bottle_qty*(btl_price-state_btl_cost)) DESC
        ) rn
    FROM sales 
    GROUP BY county, category_name 
) t
WHERE rn = 1
ORDER BY profit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM