在select語句中從SUM返回前5位

[英]Return top 5 from SUM in select statement


I need to return the following statement but I only want to return the TOP 5 of each Sale value only.....not all the records.

我需要返回以下聲明,但我只想返回每個Sale值的TOP 5 .....並非所有記錄。

Select ID, Code, sum(Sale) as Sale from TableName
Where Code = 11
Group By ID, code

I do not want this!

我不想要這個!

Select TOP 5 ID, Code, sum(Sale) as Sale from TableName
Where Code = 11
Group By ID, code

6 个解决方案

#1


3  

With Cte as 
( Select  ID, Code, sale as Sales ,
  row_number() over (partition by ID,code order by sale desc) as row_num 
  from TableName where code=11
)
Select Id,code,sum(sales) from cte 
GROUP BY ID, code
WHERE row_num < 6

#2


1  

WITH TopSales AS (
  SELECT *, RANK() OVER (PARTITION BY ID, Code ORDER BY Sale DESC) saleRank
  FROM TableName
)
SELECT ID, Code, SUM(Sale) AS Sale
  FROM TopSales
  WHERE (Code = 11) AND (saleRank <= 5)
  GROUP BY ID, code

#3


0  

select id, code, SUM (sale) 
from
(
    select id, code, sale, 
        ROW_NUMBER() over(partition by id, code order by sale desc) rn 
    from tablename
) v
where rn<=5
group by id, code 

#4


0  

Probably you need something like:

可能你需要這樣的東西:

;WITH sales (
SELECT
 id, 
 code,
 sale,
 ROW_NUMBER() OVER (PARTITION BY id, code ORDER BY sales DESC) n
FROM
 TableName
WHERE
 Code = 11
)
SELECT
 id, code, sum(sale) sale
FROM
 sales
WHERE
 n <= 5
GROUP BY
 id,
 code

ROW_NUMBER() and PARTITION BY help to find last 5 sales. Then you SUM only top (highest) 5.

ROW_NUMBER()和PARTITION BY幫助查找最近5次銷售。那么你只有SUM(最高)5。

This query returns sum of top 5 sales for each (id, code) group.

此查詢返回每個(id,code)組的前5個銷售額的總和。

#5


0  

If you want to return just the top 5 results for each group you could do this:

如果您只想返回每組的前5個結果,您可以這樣做:

with cte as 
(ID, Code, Sale,ROW_NUMBER() over(partition by  ID,
Code order by (select 0)) rownum
from TableName)
Select ID, Code, sum(Sale) as Sale from cte
Where Code = 11
and rownum<=5
Group By ID, code

If you want to return top 5 results with highest salary for each group you could do this:

如果您想要為每個組返回薪水最高的前5個結果,您可以這樣做:

with cte as 
(ID, Code, Sale,ROW_NUMBER() over(partition by  ID,
Code order by Sale desc) rownum
from TableName)
Select ID, Code, sum(Sale) as Sale from cte
Where Code = 11
and rownum<=5
Group By ID, code

#6


-1  

select id, code, sum(sale) as sale from tablename
where code = 11
group by id, code
order by sum(sale) desc
limit 5

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/07/25/725847ae3a924fce6c345f0fc8d8b9da.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com