mysql 行号无法正常处理订单

mysql row number is not working properly with order

我有一个包含下表的商店数据库:

1 - 提供者(提供者 ID,姓名,国家/地区)

2 - 产品(ProductID,ProviderID,ProductPrice)

3 - 命令(CommandID、ProductID、ProductQuantity、CommandDate)

我做了一个按年计算收益的查询

SELECT EXTRACT(YEAR FROM COMMAND_DATE) AS year, 
SUM(PRODUCT_PRICE*PRODUCT_QUANTITY) AS gain
FROM PRODUCT JOIN COMMAND ON PRODUCT.PRODUCT_ID=COMMAND.PRODUCT_ID
GROUP BY year
ORDER BY year

这是输出:

现在我想像 Oracle 一样显示行号,所以我使用了这个查询:

SET @currentRow = 0;
SELECT @currentRow := @currentRow + 1 AS counter,
EXTRACT(YEAR FROM COMMAND_DATE) AS year,
SUM(PRODUCT_PRICE*PRODUCT_QUANTITY) AS gain
FROM PRODUCT JOIN COMMAND ON PRODUCT.PRODUCT_ID=COMMAND.PRODUCT_ID
GROUP BY year
ORDER BY year

但是我没有得到我想要的

看来顺序影响了行号。我希望它从 1 开始。不能按柜台订购,因为我需要按年订购。

这就是我想要的样子:

1 2014 1863
2 2015 889
3 2016 2626
...

对于group by,你需要一个子查询:

SELECT (@currentRow := @currentRow + 1) AS counter, y.*
FROM (SELECT EXTRACT(YEAR FROM COMMAND_DATE) AS year,
             SUM(PRODUCT_PRICE*PRODUCT_QUANTITY) AS gain
      FROM PRODUCT JOIN
           COMMAND
           ON PRODUCT.PRODUCT_ID = COMMAND.PRODUCT_ID
      GROUP BY year
      ORDER BY year
     ) y CROSS JOIN
     (SELECT @currentRow := 0) params;

或者,如果您使用的是 MySQL 8+,则可以使用 ROW_NUMBER() OVER (ORDER BY YEAR)