0

我在这样的表中有数据:

 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

如何通过查询做到这一点?其中“ no ”是(如)自动增量数。

4

2 回答 2

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;
于 2013-03-27T10:27:55.017 回答
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
于 2013-03-27T10:33:10.683 回答