2

次のステートメントを返す必要がありますが、各Sale値のTOP5のみを返したいのですが.....すべてのレコードではありません。

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 に答える