3

我有一个表,由一组组组成,例如每组五行。每个组中的每一行都具有date该组唯一的值。

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

如果您想知道,我当前的查询如下所示:

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

非常感谢。

4

2 回答 2

5

这样的事情呢?

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
于 2012-08-03T21:54:35.303 回答
2

您不需要用户变量来回答您正在执行的查询。您是否有理由要使用用户变量(例如,模拟排名函数?)

如果不:

-- 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
于 2012-08-03T22:03:08.000 回答