开票流程对上个月26号到本月25号的服务进行分组。所以我想按client_id分组他们每个月要付多少钱。
+-----------+-----------+------------+-------+--------------+
| person_id | client_id | service_id | price | service_date |
+-----------+-----------+------------+-------+--------------+
| 101 | 1001 | 301 | 1000 | 2019-11-20 |
+-----------+-----------+------------+-------+--------------+
| 106 | 1001 | 301 | 1000 | 2019-11-24 |
+-----------+-----------+------------+-------+--------------+
| 102 | 1002 | 301 | 1000 | 2019-11-25 |
+-----------+-----------+------------+-------+--------------+
| 105 | 1001 | 301 | 1000 | 2019-11-26 |
+-----------+-----------+------------+-------+--------------+
| 103 | 1002 | 301 | 1000 | 2019-12-02 |
+-----------+-----------+------------+-------+--------------+
| 111 | 1002 | 301 | 1000 | 2019-12-05 |
+-----------+-----------+------------+-------+--------------+从上述数据中,我预计会出现以下情况:
+-----------+-----------+------------+
| client_id | total | month |
+-----------+-----------+------------+
| 1001 | 2000 | november |
+-----------+-----------+------------+
| 1002 | 1000 | november |
+-----------+-----------+------------+
| 1001 | 1000 | december |
+-----------+-----------+------------+
| 1002 | 2000 | december |
+-----------+-----------+------------+编辑: service_date是%d/%m/%Y格式的日期
EDIT2:我将service_date的日期格式更改为%Y-%m-%d
Db-fiddle:https://www.db-fiddle.com/f/v1Xty9c1SAp2PfaWCC4WvK/0
发布于 2019-12-31 11:15:07
要获得所需的结果,您需要按调整后的月份(和年份)进行分组。计算这些值的最简单方法是利用MySQL在数值上下文中将布尔值视为1或0这一事实,因此我们可以使用:
(MONTH(service_date) + (DAY(service_date) >= 26) - 1) % 12 + 1 AS month_num
YEAR(service_date) + (MONTH(service_date) = 12 AND DAY(service_date) >= 26) AS year由于我们必须使用这些值来生成月份名称(但我们需要用于排序的数值),因此在子查询中计算它们是最简单的(如果您使用的是MySQL 8+,则是CTE ):
SELECT client_id,
total,
year,
MONTHNAME(CONCAT_WS('-', year, month_num, '01')) AS month
FROM (SELECT client_id,
SUM(price) AS total,
(MONTH(service_date) + (DAY(service_date) >= 26) - 1) % 12 + 1 AS month_num,
YEAR(service_date) + (MONTH(service_date) = 12 AND DAY(service_date) >= 26) AS year
FROM mytable
GROUP BY client_id, month_num, year
) t
ORDER BY client_id, year, month_num输出(用于我的扩展演示)
client_id total year month
1001 2000 2019 November
1001 1000 2019 December
1001 2000 2020 January
1002 1000 2019 November
1002 2000 2019 December
1002 1000 2020 Januaryhttps://stackoverflow.com/questions/59538395
复制相似问题