如何在“分组依据”查询中创建具有自动增量编号的假列

时间:2013-03-27 10:17:20

标签: mysql

我在这样的表中有数据:

 fgid   qty   ntid
 1      100   10
 2      90    10
 6      200   11
 1      80    11
 1      120   12
 6      100   12
 6      30    13

我查询:

SELECT fgid, SUM(qty) AS total_qty, COUNT(ntid) AS nt_count FROM sofg 
GROUP BY fgid

结果是:

 fgid   total_qty   nt_count
 1      300         3
 2      90          1
 6      330         3

然后我想做这样的结果

no    fgid    total_qty   nt_count
1     1       300         3
2     2       90          1
3     6       330         3

如何通过查询执行此操作?其中“”是(如)自动增量编号。

2 个答案:

答案 0 :(得分:1)

尝试此查询。

SELECT 
  @rownum := @rownum + 1 rownum, 
  t.* 
  FROM (SELECT @rownum:=0) r, 
  (
   SELECT fgid, SUM(qty) AS total_qty, COUNT(ntid) AS nt_count FROM sofg GROUP BY fgid
  ) t;

答案 1 :(得分:1)

与Dhinakaran的答案基本相同,但没有必要将整个主查询放入子查询中。他的回答可能更令人赏心悦目,但请接受Dhinakaran的回答,因为他的速度更快。

SELECT 
@rownum:=@rownum + 1 as rownumber,
fgid, 
SUM(qty) AS total_qty, 
COUNT(ntid) AS nt_count 
FROM sofg
, (select @rownum:=0) v 
GROUP BY fgid