MySQL increment user variable when value changes

大城市里の小女人 提交于 2019-12-01 08:19:47

What about something like this?

SELECT 
    (CASE WHEN @date <> date THEN @row := @row +1 ELSE @row END) AS rownum, 
    @date:= date, 
    date
FROM ( SELECT @row := 0, @date := NOW() ) r, stats

You don't need a user variable to answer the query that you are doing. Is there a reason you want to use the user variable (for example, to emulate a ranking function?)

If not:

-- how many groups are there?
select count(distinct date) distinct_groups from table;

-- each group and count of rows in the group
select date, count(*) from table group by date;

-- if you want the Nth row from each group, assuming you have an auto_increment called id:
select *
  from table
  join ( select date, max(id) id
           from table
          group by date
  ) sq
  on table.id = sq.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!