MySQL在值更改时增加用户变量

我有一个由多组组成的表格,例如每组五行.每个组中的每一行都拥有该组独有的 date 值.

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.

我想在查询中做的是遍历表,并在此 date 值更改时增加用户变量 (@count).也就是说,@count 应该等于组数,而不是行数.

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

非常感谢.

推荐答案

这样的事情怎么样?

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

相关文章