Reputation: 5
I have a following table,
Code Desc Curr_Year
-------------------------
AB XYZ 2019
And I am looking for a SQL query which repeats the same row from year 1993 to 2019.
The output should look like this:
Code Desc Curr_Year Inc_Yr
---------------------------------
AB XYZ 2019 1993
AB XYZ 2019 1994
AB XYZ 2019 1995
AB XYZ 2019 1996
. . . .
. . . .
AB XYZ 2019 2019
I am using SQL Server 2012.
I am not a SQL expert and really struggling to get this done.
Any help would be greatly appreciated.
Upvotes: 0
Views: 74
Reputation: 2809
I would do it like:
SELECT Code
,Desc
,Curr_Year
,g.num as Inc_Yr
FROM yourtable A
CROSS JOIN (SELECT TOP 26 1992+ ROW_NUMBER() OVER (ORDER BY [object_id]) as num FROM sys.all_objects) g
In a first step generating a list of values of all years you need, then a simple CROSS JOIN
.
If you are not allowed to use the table sys.all_objects
, you could still use a list of values. Have a look at the second answer to this question:
How can I select from list of values in SQL Server
Upvotes: 0
Reputation: 48207
;WITH Years AS
(
SELECT Inc_Yr = ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects
)
SELECT Table1.*, Inc_Yr
FROM Years
CROSS JOIN Table1
WHERE Inc_Yr BETWEEN 1993 AND 2019
ORDER BY Inc_Yr;
Upvotes: 1