Question

Usually this works the other way around, but I'd like to break single records into multiple records through SQL.

We store a range of with a begin and end date, but are needing to export a record for each year in the range.

Example: TECH_ID has a begin_date of 2009 and end_date of 2011. We need to export 3 records of 2009, 2010, and 2011.

How can this be accomplished?

Was it helpful?

Solution

You require a numbers table:

CREATE TABLE Numbers
(
    Number INT NOT NULL,
    CONSTRAINT PK_Numbers 
        PRIMARY KEY CLUSTERED (Number)
        WITH FILLFACTOR = 100
)

INSERT INTO Numbers
SELECT
    (a.Number * 256) + b.Number AS Number
FROM 
    (
        SELECT number
        FROM master..spt_values
        WHERE 
            type = 'P'
            AND number <= 255
    ) a (Number),
    (
        SELECT number
        FROM master..spt_values
        WHERE 
            type = 'P'
            AND number <= 255
    ) b (Number)
GO

Now that you have a numbers table...

SELECT DISTINCT
    n.Number
FROM
    Numbers n 
    JOIN TECH_ID t 
        ON n.Number BETWEEN t.begin_date AND t.end_date

OTHER TIPS

Create a table with a row per year (some RDBMS's have shortcuts). Then do

Select
  t.*,
  y.Year
From
  Years y
    Inner Join
  tech_id t
    On Year(t.begin_date) <= y.Year And Year(t.end_date) >= y.Year

As I read your question, it was not clearly mentioned about the sample data. By the way, I wrote this as an example to put one record to three records based on whatever you have.

Select  *
    From    (
        Select  1   As  Id
        ,   'Test'  As  Name
    )   As  SampleRecord
    Cross   Join
        (
        Select  2009    As  Year
    Union   Select  2010
    Union   Select  2011
    )   As  Years

Cheers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top