【问题标题】:getting the ranking of the rows in mysql group by ORDER BY statements通过 ORDER BY 语句获取 mysql 组中行的排名
【发布时间】:2013-09-24 02:41:35
【问题描述】:

我有一个包含以下字段的表:季节、收藏、产品密钥、聚合销售。我想添加额外的排名列(自动递增),它应该按季节、收藏、aggregated_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

【问题讨论】:

标签: mysql group-by sql-order-by auto-increment


【解决方案1】:

这个应该能胜任,虽然效率不高

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

【讨论】:

    【解决方案2】:

    以下查询解决了我的问题

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 2017-12-07
      相关资源
      最近更新 更多