Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Please help with this Query

Author  Topic 

anchoredwisdom
Starting Member

22 Posts

Posted - 2012-11-10 : 04:45:11
Hi Gurus,

Can you please help me with this query.
Just a single table

I have a table called test with 5 columns
ID, GRP,Country, Year, Wage

ID WAGE GRP CNTY YR
1 25000 A USA 1996
1 30000 A USA 1997
1 35000 A USA 1998
1 40000 A USA 1999
1 45000 A USA 2000
2 125000 A USA 1996
2 130000 A USA 1997
2 135000 A USA 1998
2 140000 A USA 1999
2 145000 A USA 2000
20 25000 A GER 1996
20 35000 A GER 1998
20 40000 A GER 1999
20 45000 A GER 2000
21 125000 A GER 1996
21 130000 A GER 1997
21 135000 A GER 1998
21 145000 A GER 2000


As you can see for ID 21 there is no data for year 1999
and for ID20 there is no data from year 1997.

I have to write a Select statement to display above data and where ever records for a particular year is not present display NULL correspondingly.

Appreciate your suggestions

Thanks


sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-11-10 : 07:49:42
You should create a reference table that lists all the years that are of interest to you and then left join to that table. You could even construct one on the fly like this and use that:
SELECT
t.id, t.wage, t.grp, t.cnty, c.Yr
FROM
(VALUES (1996),(1997),(1998),(1999),(2000)) c(Yr)
LEFT JOIN test t ON t.Yr = c.Yr
Go to Top of Page
   

- Advertisement -