使用parent_id进行SUM和分组

时间:2016-03-08 04:15:18

标签: mysql sql ruby-on-rails ruby ruby-on-rails-4

我有桌子:

分类

+----+-----------+---------------+
| id | parent_id | name          |
+----+-----------+---------------+
|  1 |      NULL | Dong ho nam   |
|  2 |         1 | dong ho nam 1 |
|  3 |         1 | dong ho nam 2 |
|  4 |         1 | dong ho nam 3 |
|  5 |         1 | dong ho nam 4 |
|  6 |      NULL | Dong ho nu    |
|  7 |         6 | Dong ho nu 1  |
|  8 |         6 | Dong ho nu 2  |
|  9 |         6 | Dong ho nu 3  |
+----+-----------+---------------+

和表产品

+----+-------------+---------------+
| id | category_id | quantity      |
+----+-------------+---------------+
|  1 |         6   | 10            |
|  2 |         3   | 2             |
|  3 |         3   | 4             |
|  4 |         2   | 12            |
|  5 |         4   | 6             |
|  6 |         2   | 0             |
|  7 |         6   | 8             |
|  8 |         8   | 22            |
|  9 |         9   | 4             |
+----+-------------+---------------+

我想选择类别,总和(数量)
//(所有产品数量属于category和category.parent_id = null)

结果

+----+-----------+---------------+-----------+
| id | parent_id | name          | quantity  |
+----+-----------+---------------+-----------+
|  1 |      NULL | Dong ho nam   |     24    |
|  6 |      NULL | Dong ho nu    |     44    |
+----+-----------+---------------+-----------+

如何使用sql查询(或rails)可以实现上述结果。  韩国社交协会。

1 个答案:

答案 0 :(得分:0)

您需要在父级和子级上聚合。这样的事情应该很接近:

select c.id, p.quantity + coalesce(sum(p2.quantity),0) 
from categories c
    join (
        select category_id, sum(quantity) quantity
        from products 
        group by category_id) p on c.id = p.category_id 
    left join categories c2 on c.id = c2.parent_id
    left join products p2 on c2.id = p2.category_id
where c.parent_id is null
group by c.id