簡體   English   中英

選擇具有最大總值的SQL Server行

[英]Select row that has max total value SQL Server

我有以下方案(2個表):

客戶(編號,名稱)和銷售(編號,客戶編號,日期,總和)

如何選擇以下數據?

1)一直以來都是最佳客戶(“客戶”的“總和”列中有“最大總價值”)

例如,我有2個表(分別為客戶和銷售):

id    CustomerName      
---|--------------
1  | First         
2  | Second 
3  | Third 



id  CustomerId  datetime     Sum
---|----------|------------|-----
1  | 1        | 04/06/2013 | 50
2  | 2        | 04/06/2013 | 60
3  | 3        | 04/07/2013 | 30
4  | 1        | 03/07/2013 | 50
5  | 1        | 03/08/2013 | 50
6  | 2        | 03/08/2013 | 30
7  | 3        | 24/09/2013 | 20

所需結果:

CustomerName TotalSum
------------|--------
 First      | 150

2)當年每月的最佳客戶(與上一個相同,但當年每月的最佳客戶)

謝謝。

嘗試使用此方法,始終獲得最佳客戶

SELECT Top 1 WITH TIES c.CustomerName, SUM(s.SUM) AS TotalSum
FROM Customer c JOIN Sales s ON s.CustomerId = c.CustomerId
GROUP BY c.CustomerId, c.CustomerName
ORDER BY SUM(s.SUM) DESC

一種選擇是將RANK()SUM聚合結合使用。 這將為您提供整體價值。

select customername,  sumtotal
from (
  select c.customername, 
    sum(s.sum) sumtotal,
    rank() over (order by sum(s.sum) desc) rnk
  from customer c
    join sales s on c.id = s.customerid
  group by c.id, c.customername
  ) t
where rnk = 1

在這一點上,按月和年進行分組應該是微不足道的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM