仅对父类别的递归查询 - 按期间

时间:2016-08-22 17:34:36

标签: mysql sql

在下面的SQL中,我只需要显示当前月份和年份的记录。

SELECT y.desc_category as segment, sum( x.value) as total FROM (
SELECT category.id_category, category.desc_category, category.parent_id , c.value AS value
FROM category
INNER JOIN cashbook AS c ON category.id_category = c.category_id )AS x 
INNER JOIN category AS y ON x.parent_id = y.id_category
INNER JOIN user AS u ON y.user_id = u.id
WHERE u.id = 3
GROUP BY y.desc_category

我问过这篇文章Mysql - Recursive Query for only the parent categories,但没有回复,问题是另一回事。任何人都可以帮助我

我的架构

我有下表category

id | desc_cat       | parent_id
19 | Personal       | (null)
20 | Credit Card    | 19
21 | Academy        | 19
22 | Home           | (null)
23 | Water          | 22
24 | Energy         | 22
25 | Rent           | 22

我有一个包含名称为cashbook的条目的表:

id  | value    | category_id | date
177 | 480.55   | 20          | 2016-05-01
178 | 100.00   | 24          | 2016-05-04
179 | 580.00   | 25          | 2016-05-05
180 | 80.00    | 21          | 2016-05-09
181 | 28.00    | 23          | 2016-05-11

1 个答案:

答案 0 :(得分:0)

您应该选择年份和月份作为日期..并按

分组
SELECT x.`year`, x.`month`, y.desc_category as segment, sum( x.value) as total FROM (
SELECT category.id_category, category.desc_category, category.parent_id , c.value AS value, 
       year(c.`date`) as `year` , month(c.`date`) AS `month`
FROM category
INNER JOIN cashbook AS c ON category.id_category = c.category_id ) AS x 
INNER JOIN category AS y ON x.parent_id = y.id_category
INNER JOIN user AS u ON y.user_id = u.id
WHERE u.id = 3
GROUP BY y.desc_category, x.`year`, x.`month`

按实际年份和月份过滤的简便方法是使用现在

SELECT x.`year`, x.`month`, y.desc_category as segment, sum( x.value) as total FROM (
SELECT category.id_category, category.desc_category, category.parent_id , c.value AS value, 
       year(c.`date`) as `year` , month(c.`date`) AS `month`
FROM category
INNER JOIN cashbook AS c ON category.id_category = c.category_id ) AS x 
INNER JOIN category AS y ON x.parent_id = y.id_category
INNER JOIN user AS u ON y.user_id = u.id
WHERE u.id = 3
GROUP BY y.desc_category, x.`year`, x.`month`
having x.`year` = year(now())  and x.`month` = month(now())