在select语句中从SUM返回前5位

时间:2012-07-25 07:58:56

标签: sql sql-server tsql

我需要返回以下声明,但我只想返回每个Sale值的TOP 5 .....并非所有记录。

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

我不想要这个!

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

6 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

可能你需要这样的东西:

;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()PARTITION BY有助于查找最近5次销售。然后你SUM只有最高(最高)5。

此查询返回每个(ID,代码)组的前5个销售额的总和。

答案 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)

如果您只想返回每组的前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

如果您希望返回每组最高薪水的前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

答案 5 :(得分:-1)

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