创建以各种方式分隔一条线的视图

Create View that separates a line in various

我有这个table:

-- Product --
id_product
date-begin
date_end
period

并填写:

id_project | date_begin | date_end | period
1 | 2015-01-01 | 2016-01-01 | 1 month
2 | 2015-12-01 | 2015-12-29 | 1 week

我想让视图显示它:

id_project | date_payment
1 | 2015-02-01
1 | 2015-03-01
1 | 2015-04-01
...
1 | 2016-01-01
2 | 2015-12-01
2 | 2015-12-08
2 | 2015-12-15
2 | 2015-12-22
2 | 2015-12-29

如何将一行分成几行?

你只需要 日期 table 然后 Inner Join 你的 table 和 dates table

select * 
from yourtable A
inner join Dates_table b 
on b.dates between a.date_begin and a.date_end 

如果您正在使用 Sql Server 检查此 link 日期 table 代码

这是一个非常基本的示例,说明您可以采取哪些措施来解决您的问题。

它做的第一件事是为您创建一些数字视图,以便我们稍后加入。这些是一些笛卡尔连接来创建大量数字.. 16 到 100 万..

CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL 
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15;

CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
     FROM generator_16 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_256 hi;

在此处找到该代码.. Creating a "Numbers Table" in mysql

然后您可以使用此语句创建视图。

CREATE OR REPLACE VIEW product_payment_dates
AS SELECT   p.id_project,  
        CASE  
            WHEN p.period LIKE '%month%' THEN DATE_ADD(p.date_begin,INTERVAL n.n MONTH)
            WHEN p.period LIKE '%week%' THEN DATE_ADD(p.date_begin,INTERVAL n.n WEEK)
            WHEN p.period LIKE '%day%' THEN DATE_ADD(p.date_begin,INTERVAL n.n DAY)
        END as date_payment
FROM    Product p
JOIN    generator_64k n ON (CASE 
                        WHEN p.period LIKE '%month%' THEN DATE_ADD(p.date_begin, INTERVAL n.n MONTH)
                        WHEN p.period LIKE '%week%' THEN DATE_ADD(p.date_begin, INTERVAL n.n WEEK)
                        WHEN p.period LIKE '%day%' THEN DATE_ADD(p.date_begin, INTERVAL n.n DAY)
                    END) <= p.date_end
ORDER BY p.id_project, date_payment;

这会查看期间,以确定您是否应该向 begin_date 添加月、周或天来构建列表。如果您想添加 2 个月或 3 周等,您还可以自定义它以从期间中提取间隔数。

这里是SQL Fiddle所有的东西