How to pivot dynamically with date as column

后端 未结 2 436
再見小時候
再見小時候 2020-12-02 00:01

I have a table with product id\'s and names, and another table with the stock of these products on certain dates. Such as Item1 had 6 stock on

2条回答
  •  心在旅途
    2020-12-02 00:32

    Step 1 - Fill the gaps (maybe not required)

    If your stocks table does not contain stock from every day for every product then you have to get all the dates in a month from somewhere else. You can generate them with a recursive CTE: (variable declarations are omitted)

    with dates as
    (
       select @startdate as [date]
       union ALL
       select   [date] + 1 
       from dates
       where    [date] < @enddate
    )
    select  @strDays = COALESCE(@strDays + ', ['+ convert(varchar(8), [date],112) + ']', '['+ convert(varchar(8), [date],112) + ']') 
    from    dates;
    

    You can use your preferred date format but it's important to maintain it in all queries.

    Step 2 - Bring data to a normal form. You can chose to store it in a temporary table or you can use a CTE again and combine this step with step 3.

    Join dates (from above) with products (full) and with stock (left) so you obtain a table like this:

    date
    product_id    
    items
    

    For products and dates where stock is not available you display 0. isnull will do the trick. Make sure the date column is converted to varchar in the same format as in CTE above.

    Step 3 - pivot the table (obtained at step 2) by date column in a dynamic query.

    I can give you more details but not right now. You can see something similar in another response: Spread distinct values over different columns

提交回复
热议问题