SQL财政日期,平面文件,痛苦

时间:2011-03-22 03:59:22

标签: python sql sqlite

使用sqlite3,python

我有一个糟糕的遗留文件 legacy_sales

item | year | week | mon | tue | wed | thu | fri | sat |sun 
4444   2011     29    10    0     4    15     18    25   30

我有一个很棒的新文件销售(这是上面'mon'条目的一个例子):

item | units |     date
4444   10       2011-03-14

我在另一个表财政

中有会计年度的开始日期
year | start_date
2011   2010-08-30

有了这些信息,最有效和最有效的方法是:

insert into sales from (insert magic here) 

不使用任何UDF ......

有任何经验吗?

2 个答案:

答案 0 :(得分:1)

insert into sales from (
    -- here be magic
    select  item, units, DATEADD(day, DayInYear, start_date)
    from    (
        select  item,
                year,
                (week - 1) * 7 + 0 as DayInYear,
                mon as Units
        from    legacy_sales
        union all
        select  item, year, (week - 1) * 7 + 1, tue
        from    legacy_sales
        union all
        select  item, year, (week - 1) * 7 + 2, wed
        from    legacy_sales
        union all
        select  item, year, (week - 1) * 7 + 3, thu
        from    legacy_sales
        union all
        select  item, year, (week - 1) * 7 + 4, fri
        from    legacy_sales
        union all
        select  item, year, (week - 1) * 7 + 5, sat
        from    legacy_sales
        union all
        select  item, year, (week - 1) * 7 + 6, sun
        from    legacy_sales
        ) ls
        inner join fiscal on
            fiscal.year = ls.year
)

答案 1 :(得分:0)

转换自:legacy_sales

item | year | week | mon | tue | wed | thu | fri | sat |sun 
4444   2011     29    10    0     4    15     18    25   30

to:sales

item | units |     date
4444   10       2011-03-14

在英语python中需要这个:

for row in legacy_sales:
    year = row['year']
    week = row['week']
    for day_name in "mon | tue | wed | thu | fri | sat |sun".split(" | "):
        some how turn (year, week, day_name) into year_month_day
        insert into sales values (row['item'], row[day_name], year_month_day)