-1

我有一个包含以下字段的表:季节、集合、product_key、aggreged_sale。我想添加额外的排名列(自动递增),它应该按季节、收藏、聚合销售的顺序排列

假设我有

ss, f1, 2, 5
ss, f1, 3, 10
ss, f1, 1, 11
ss, f2, 4, 7
ss, f2, 5, 11

预期输出是

ss, f1, 2, 5,1
ss, f1, 3, 10,2
ss, f1, 1, 11,3
ss, f2, 4, 7,1
ss, f2, 5, 11,2
4

2 回答 2

0

这个应该可以完成这项工作,尽管效率不高

select col1, col2,col3,col4,
(
 select count(*) from myTable where 
  col1<t.col1 or
 (col1=t.col1 and col2<t.col2) or
 (col1=t.col1 and col2=t.col2 and col4<t.col4)
)+1 as col5
FROM myTable t
order by col1,col2

笔记:

  • 您需要指定当 2 条记录相同时您的排名应该是什么
  • 如果要将结果保存在表中,则需要使用 UPDATE
  • ORDER BY 是可选的
  • 在 sql server 中有一个内置函数ROW_NUMBER
于 2013-09-19T06:45:36.910 回答
0

以下查询解决了我的问题

set @type = '';
set @num  = 1;
select
   ap.*,
   @num := if(@type = concat(collection,forecast_name), @num + 1, 1) as row_number,
   @type := concat(collection,forecast_name) as dummy
from rank_processing.aggregate_product ap;
于 2013-09-19T06:49:32.063 回答