我有下表
id | add_card_id | rate | category | category_count | counts | total
7597 | 723 | 3 | 7 | 1 | 300 | 108
7596 | 723 | 3 | 9 | 1 | 500 | 180
7594 | 723 | 3 | 11 | 1 | 400 | 240
7593 | 723 | 5 | 10 | 2 | 400 | 240
7593 | 723 | 5 | 13 | 2 | 400 | 240
我想获取
total
(列名)的总和,其中rate
相同,但总和仅包括第n个。在具有最大总数的行中,第n个由category_count
(列名)定义。例如,前三列的比率为3,category_count为1,因此前三行的总和(总数)为240,因为240> 180> 108;对于后两行,比率为5,category_count为2,因此240 + 240 = 480,我想要720 = 240(来自前三行)+ 480(来自后两行)。
我尝试了以下查询
SELECT SUM(total)
FROM (SELECT MAX(total)
FROM tableName
GROUP BY rate, category_count) as newTable
它给了我240+ 240,所以我怎么能用
category_count
(column)给出限制? 最佳答案
您可以通过动态分配变量在MySql中模拟ROW_NUMBER和PARTITION BY
SELECT rate, SUM(total)
FROM
(
SELECT total, rate, category_count,
-- Row num counter, resets at each different rate
@row_num := IF(@prev_rate=rate, @row_num+1, 1) AS RowNum,
@prev_rate := rate -- Track to see if we are in the same rate
FROM tableName,
(SELECT @row_num := 1) x, -- Set initial value for @row_num and @prev_rate
(SELECT @prev_rate := '') y
-- Important, must keep rates together, then order by your requirement
ORDER BY rate ASC, total DESC
) ranked
WHERE ranked.RowNum <= ranked.category_count -- Your requirement of TOP N
GROUP BY rate;
以上收益
Rate Total
3 240
5 480
如果您执行
SELECT SUM(total)
然后放下GROUP BY,则可以得到720。SqlFiddle here
编辑
似乎速率定义为(我假设您的样本数据为整数)
`rate` varchar(X) COLLATE utf8_unicode_ci
更改一行:
(SELECT @prev_rate := '' COLLATE utf8_unicode_ci) y
它将临时跟踪变量设置为与您的列相同的类型
关于mysql - MySQL查询:获取N行的总和,其中N在另一个列值中定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27665175/