How to generate multiple time series in one sql query?

前端 未结 3 1684
余生分开走
余生分开走 2021-01-18 20:06

Here is the database layout. I have a table with sparse sales over time, aggregated per day. If for an item I have 10 sales on the 01-01-2015, I will have an entry, but If I

3条回答
  •  独厮守ぢ
    2021-01-18 20:28

    First you need a table with all dates to fill the blank dates. 100 years of date mean 36,000 rows so no very big. Instead of calculate every time.

    allDates:

    date_id
    s_date
    

    or created calculating the fields

    date_id
    s_date
    doy = EXTRACT(DOY FROM s_date)
    year = EXTRACT(YEAR FROM s_date)
    

    Your base query will be SQL FIDDLE DEMO:

    SELECT           
          AD.year,
          AD.doy,           
          allitems.item_id,
          COALESCE(SUM(ED.sales), 0) as max_sales
    FROM 
        (SELECT DISTINCT item_id
         FROM entry_daily 
        ) as allitems
    CROSS JOIN alldates AD
    LEFT JOIN entry_daily ED
           ON ED.day_of_year = AD.doy
          AND ED.year = AD.year  
          AND ED.item_id = allitems.item_id
    WHERE AD.year = 2015
    GROUP BY
         AD.year, AD.doy, allitems.item_id
    ORDER BY 
         AD.year, AD.doy, allitems.item_id
    

    You will have this OUTPUT

    | year | doy | item_id | max_sales |
    |------|-----|---------|-----------|
    | 2015 |   1 |      A1 |        20 |
    | 2015 |   1 |      A2 |        11 |
    | 2015 |   2 |      A1 |         0 |
    | 2015 |   2 |      A2 |         0 |
    | 2015 |   3 |      A1 |         0 |
    | 2015 |   3 |      A2 |         0 |
    | 2015 |   4 |      A1 |         0 |
    | 2015 |   4 |      A2 |         0 |
    | 2015 |   5 |      A1 |         0 |
    | 2015 |   5 |      A2 |         0 |
    | 2015 |   6 |      A1 |         0 |
    | 2015 |   6 |      A2 |         0 |
    | 2015 |   7 |      A1 |        39 |
    | 2015 |   7 |      A2 |         0 |
    | 2015 |   8 |      A1 |         0 |
    | 2015 |   8 |      A2 |         0 |
    | 2015 |   9 |      A1 |         0 |
    | 2015 |   9 |      A2 |         0 |
    | 2015 |  10 |      A1 |         0 |
    | 2015 |  10 |      A2 |         0 |
    

    Then you need install tablefunc

    and use crosstab to pivot this table SAMPLE

提交回复
热议问题