Mysql 根据日期将值拆分为多行的视图
Mysql View where a value is split over multiple rows according to date
MySql版本:5.6.47
假设我有一个 table 这样的:
[from:Datetime][to:Datetime][amount:Decimal(10,2)]
[2020/01/15 ][2020/02/15 ][300 ]
我想用它创建一个这样的视图:
[period:char(7)][amount:Decimal(10,2)]
[2020/01 ][150 ]
[2020/02 ][150 ]
开始日期和结束日期在单个月份中分开。该金额乘以该特定月份的天数乘以从和到之间的总天数。从和到可以跨越 n 个月。
这有可能吗?还是我在浪费时间研究这个?
假设范围内的月数不超过 100:
SELECT id,
datefrom,
datetill,
amount,
monthstart,
monthfinish,
amount * (DATEDIFF(LEAST(datetill, monthfinish), GREATEST(datefrom, monthstart)) + 1) / (DATEDIFF(datetill, datefrom) + 1) monthamount
FROM ( SELECT test.*,
(test.datefrom - INTERVAL DAY(test.datefrom) - 1 DAY) + INTERVAL numbers.num MONTH monthstart,
LAST_DAY((test.datefrom - INTERVAL DAY(test.datefrom) - 1 DAY) + INTERVAL numbers.num MONTH) monthfinish
FROM test
JOIN ( SELECT t1.num*10+t2.num num
FROM (SELECT 0 num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1
JOIN (SELECT 0 num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2
) numbers
HAVING monthstart <= test.datetill
AND monthfinish >= test.datefrom
) subquery
ORDER BY id, monthstart;
PS。如果总和在最后一位不匹配,请不要感到惊讶。
MySql版本:5.6.47
假设我有一个 table 这样的:
[from:Datetime][to:Datetime][amount:Decimal(10,2)]
[2020/01/15 ][2020/02/15 ][300 ]
我想用它创建一个这样的视图:
[period:char(7)][amount:Decimal(10,2)]
[2020/01 ][150 ]
[2020/02 ][150 ]
开始日期和结束日期在单个月份中分开。该金额乘以该特定月份的天数乘以从和到之间的总天数。从和到可以跨越 n 个月。
这有可能吗?还是我在浪费时间研究这个?
假设范围内的月数不超过 100:
SELECT id,
datefrom,
datetill,
amount,
monthstart,
monthfinish,
amount * (DATEDIFF(LEAST(datetill, monthfinish), GREATEST(datefrom, monthstart)) + 1) / (DATEDIFF(datetill, datefrom) + 1) monthamount
FROM ( SELECT test.*,
(test.datefrom - INTERVAL DAY(test.datefrom) - 1 DAY) + INTERVAL numbers.num MONTH monthstart,
LAST_DAY((test.datefrom - INTERVAL DAY(test.datefrom) - 1 DAY) + INTERVAL numbers.num MONTH) monthfinish
FROM test
JOIN ( SELECT t1.num*10+t2.num num
FROM (SELECT 0 num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1
JOIN (SELECT 0 num UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2
) numbers
HAVING monthstart <= test.datetill
AND monthfinish >= test.datefrom
) subquery
ORDER BY id, monthstart;
PS。如果总和在最后一位不匹配,请不要感到惊讶。