2

我需要返回以下语句,但我只想返回每个销售值的 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
4

6 回答 6

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
于 2012-07-25T08:02:07.730 回答
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
于 2012-07-25T08:08:07.510 回答
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、code)组的前 5 个销售额的总和。

于 2012-07-25T08:03:43.240 回答
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 
于 2012-07-25T08:05:39.097 回答
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
于 2012-07-25T08:39:37.777 回答
-1
select id, code, sum(sale) as sale from tablename
where code = 11
group by id, code
order by sum(sale) desc
limit 5
于 2012-07-25T08:02:26.110 回答