我有下表,
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
(列)给出限制?
最佳答案
可以通过动态赋值变量模拟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。
编辑
似乎速率定义为(我假设您的样本数据中的整数)
`rate` varchar(X) COLLATE utf8_unicode_ci
改变一行:
(SELECT @prev_rate := '' COLLATE utf8_unicode_ci) y
这会将临时跟踪变量设置为与您的列相同的类型
关于MySql 查询 : Get sum of N rows where N is defined in another column value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27665175/