0

MySql 版本:5.6.47

假设我有一张这样的桌子:

[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 个月。

这是可能的还是我在浪费时间研究这个?

4

1 回答 1

1

假设某个范围内的月数不超过 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。如果总和在最后一位不匹配,请不要感到惊讶。

于 2020-05-19T09:57:32.673 回答