如何在Postgresql中查询MAX(SUM(关系))?

时间:2018-02-08 17:22:04

标签: sql database postgresql

我已经在StackOverflow上阅读了几个相关的线程,但没有一个解决了我的问题。 我有一个销售数据库,因为我需要查询花费最多的客户。 为此,我需要找到谁使用

购买了哪种产品
String JsonArrayString = "[ { 'id': 1, 'className': { 'id': 1 } }, { 'id': 2, 'className': { 'id': 2 } } ]";

Gson gson = new GsonBuilder().create();
Type listType = new TypeToken<List<Class1>>(){}.getType();
ArrayList<Class1> classess= gson.fromJson(JsonArrayString, listType);

它返回一个表格,其中包含该人的姓名以及他按升序排列的内容

上面的命令输出:

enter image description here

虽然我实际需要的是仅在SELECT sum(qty*rate) AS exp from salesdetails as s JOIN sales as ss on (ss.invno = s.invno) JOIN customer as c ON (ss.customerno = c.custno) GROUP BY(c.name) ORDER BY sum(qty*rate); 最大时才打印元组。目前我通过子查询获得结果:

sum(qty*rate)

预期产出:

enter image description here

有没有更短的方法来获得输出?

2 个答案:

答案 0 :(得分:1)

您需要row_number()distinct on

SELECT DISTINCT ON (c.name) c.name, sum(qty*rate) AS exp
FROM salesdetails s JOIN
     sales ss
     on (ss.invno = s.invno) JOIN
     customer c
     ON (ss.customerno = c.custno)
GROUP BY c.name
ORDER BY c.name, sum(qty*rate) DESC;

答案 1 :(得分:1)

你在寻找这样的东西:

select * 
from (
       SELECT c.Name, sum(qty*rate) 
       AS exp from salesdetails as s JOIN sales as ss on (ss.invno = s.invno) 
       JOIN customer as c ON (ss.customerno = c.custno) 
       GROUP BY(c.name) 
       ORDER BY sum(qty*rate) desc
     ) t
limit 1;