简体   繁体   English

SQL查询汇总的最大值

[英]SQL query max value of a summarize

I am currently learning SQL and I am required to execute some SQL queries. 我目前正在学习SQL,并且需要执行一些SQL查询。 There is one particular query that I fail to implement. 我没有实现一个特定的查询。

Which are the clients who have (totally) the most expensive orders? 哪些客户(总的来说)是最昂贵的订单?

customerid and total value of all orders of the same customer must be returned as result. 结果必须返回同一个客户的所有订单的customeridtotal value

The table is: 该表是:

Salesorderheader : Salesorderheader

salesorderid (int)   customerid (int)   totaldue (double)  
       1                 32000            3.20000  

The database system I use is Postgresql. 我使用的数据库系统是Postgresql。 The query I got so far is: 到目前为止,我得到的查询是:

SELECT totaldue, customerid 
FROM salesorderheader   
WHERE totaldue = (SELECT max(totaldue) FROM salesorderheader);

This query is wrong because a new value labeled as total_value (total value of all orders of the same customer) or something similar must be returned instead. 此查询是错误的,因为必须返回一个标记为total_value的新值(同一客户的所有订单的总价值)或类似的值。

I know there that the SQL function sum() must be used combined with GROUP BY customerid) , but so far I failed to implement the correct query. 我知道那里必须将SQL函数sum()GROUP BY customerid)结合使用,但是到目前为止,我未能实现正确的查询。

Thank you for your time. 感谢您的时间。

NOTE: if I broke any site rules or this post is duplicate let me now and I'll delete this post immediately 注意:如果我违反了任何网站规则,或者该帖子重复,请立即联系我,我将立即删除该帖子

表样

在此处输入图片说明

this gives biggest expences by clients: 这为客户带来了最大的收益:

SELECT distinct max(totaldue) over (partition by customerid),customerid 
FROM salesorderheader
order by 1 desc 
;

this shows the most wasting client between all: 这显示了所有客户端之间浪费最多的客户端:

select sum(totaldue) over (partition by customerid),customerid 
    FROM salesorderheader
    order by 1 desc 
limit 1
    ;

select top 1 customer_id, sum(total_due) as total 选择前1个customer_id,总和(total_due)

into #top 进入#top

from salesorderheader 来自salesorderheader

group by customer_id 按customer_id分组

order by sum(total_due) desc; 按sum(total_due)desc排序;

select * from #top t 从#top t中选择*

inner join salesorderheader soh 内部加入salesorderheader soh

on soh.customer_id = t.customerid; 在soh.customer_id = t.customerid上;

drop table #top; 放下桌子#top;

I apologize for the formatting, I'm on mobile 抱歉,我正在使用手机

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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