Question

I have two tables as follows:

Table 1

Columns - oppproductid, SKU, Price, Quantity, Date
Values  - PR1, ABCSKU1, 1000,500, 10/2013 

Table 2

Columns -  opproductid, month_1, Month_2, Month_3, Month_4...Month_36
Values  -  PR1, 200, 100, NULL, 200...

The tables are 1-1. I need to get one row for each value in the month column that is not null for each record and calculate the date based on the months that are not null assuming that Month_1 is the date column in the primary table so the ideal result set based on the sample values is:

oppproductid  SKU      Price  Quantity  Date      Deployment
PR1           ABCSKU1  1000   500       10/2013   200
PR1           ABCSKU1  1000   500       11/2013   100
PR1           ABCSKU1  1000   500       1/2014    200

NOTES:

  • Month_3 is NULL so 12/2013 does not yield results.
  • There are 36 months in the second table with the only requirement that one has to contain data.
  • Month_1 always equals the date on the first table.

Any help is appreciated.

Was it helpful?

Solution

  1. Store your data using the proper data types. Dates should be date fields.
  2. Normalise your data structures to make querying easier.
  3. Try this

.

set dateformat dmy

select 
    t1.oppproductid,
    t1.SKU,
    t1.Price,
    t1.Quantity,
    dateadd(month, monthno-1, convert(date, '1/' + [date])), 
    deployment
from table1 t1
    inner join
    (
        select *, convert(int,substring(mth,7,2)) as monthno from table2
            unpivot (deployment for mth in (month_1,month_2,month_3,month_4...)) u
    ) u2
on t1.oppproductid = u2.opproductid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top