如果使用汇总

时间:2017-02-14 10:03:18

标签: mysql rollup

我正在尝试使列在汇总行上具有特定值,但是当我添加“if”时,所有其他行都会获得该列中的最后一个值。

为什么呢?什么是解决它的正确方法?

小提琴: http://rextester.com/TTYI19512

示例:

CREATE TABLE ru (ru_id INT KEY, name VARCHAR(20));
INSERT INTO ru VALUES (1, 'A'),(2, 'B');

CREATE TABLE rud (rud_id INT KEY, ru_id INT, value INT);
INSERT INTO rud VALUES (1, 1, 3), (2, 1, 5), (3, 2, 4), (4, 2, 9);

SELECT
   ru_id,
   IF(ru_id IS NULL, 'Total', name) as name,
   COUNT(rud.value),
   SUM(rud.value)
FROM ru
   INNER JOIN rud USING (ru_id)
GROUP BY ru_id WITH ROLLUP;

当前结果:

+-------+-------+------------------+----------------+
| ru_id | name  | COUNT(rud.value) | SUM(rud.value) |
+-------+-------+------------------+----------------+
|     1 | B     |                2 |              8 |
|     2 | B     |                2 |             13 |
|  NULL | Total |                4 |             21 |
+-------+-------+------------------+----------------+

预期结果:

+-------+-------+------------------+----------------+
| ru_id | name  | COUNT(rud.value) | SUM(rud.value) |
+-------+-------+------------------+----------------+
|     1 | A     |                2 |              8 |
|     2 | B     |                2 |             13 |
|  NULL | Total |                4 |             21 |
+-------+-------+------------------+----------------+

2 个答案:

答案 0 :(得分:0)

使用聚合函数包裹你的if条件,比如MAX(它没关系,因为它是一个字符串,也可能是MIN)

SELECT IFNULL(ru_id,'Total'), MAX(IF(ru_id IS NULL, 'Total', name)) as name,
 COUNT(rud.value), SUM(rud.value) 
FROM ru INNER JOIN rud USING (ru_id) 
GROUP BY ru_id WITH ROLLUP;

您可以为ID显示总数,但不能显示名称,最后一行名称将是随机的。此外,您当前的结果也不会显示总数。

答案 1 :(得分:0)

纯sql中只允许group-by中包含的聚合函数和列,因此通过在name-column周围放置一个聚合函数,它会使其成为允许的查询,并给出预期的结果。

SELECT
   ru_id,
   IF(ru_id IS NULL, 'Total', MAX(name)) as name,
   COUNT(rud.value),
   SUM(rud.value)
FROM ru
   INNER JOIN rud USING (ru_id)
GROUP BY ru_id WITH ROLLUP;

感谢@ThorstenKettner& @CBroe在评论栏中的贡献。