MySQL increment user variable when value changes

2019-02-18 19:17发布

问题:

I have a table consisting of groups of, for example, five rows each. Each row in each group possesses a date value unique to that group.

What I want to do in my query, is go through the table, and increment a user variable (@count) when this date value changes. That's to say, @count should equal the group count, rather than the row count.

My current query looks like this, in case you're wondering:

SELECT @row := @row +1 AS rownum, date
FROM ( SELECT @row := 0 ) r, stats

Thanks a lot.

回答1:

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


回答2:

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