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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Query Help.

Author  Topic 

sql_2k
Starting Member

26 Posts

Posted - 2008-06-07 : 15:13:11
Hi,

I have the below sample table for item details.

ItemID Year Qtr Value
1 2009 Q1 1200
1 2009 Q2 1205
1 2009 Q3 1302
1 2009 Q4 1980
1 2010 Q1 1709
2 2009 Q3 1800
2 2009 Q4 2000
2 2010 Q1 1990


The requirement is based of no of configured quarter the result should display data from current quarter of current year to the next no of configured quaters so data could spilt across year.

Now if no of configured quarter = 5 then below results should be fetched.

ItemID 2009Q1 2009Q2 2009Q3 2009Q4 2010Q1
1 1200 1205 1302 1980 1709
2 0 0 1800 2000 1990


Similarly the result should be displayed for 4 quarters in the above format if the configured quarter passed as 4 and so on.

Please help me writting the query /procedure for the above req.

Thanks.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-06-07 : 16:14:25
May be this:-
DECLARE @MinYear int,@MaxYear int


SELECT @MinYear=MIN(Year),@MaxYear=MAX(Year)
FROM Table

SELECT IDENTITY(int,1,1) AS ID,
@MinYear + v.Number AS Year,
q.Quarter INTO #Calendar
FROM master..spt_values v
CROSS JOIN (SELECT 'Q1' AS Quarter
UNION ALL
SELECT 'Q2'
UNION ALL
SELECT 'Q3'
UNION ALL
SELECT 'Q4')q
WHERE v.type='p'
AND @MinYear + v.Number <=@MaxYear

DECLARE @Periodlist varchar(8000)

SELECT @Periodlist=LEFT(pl.Periodlist,LEN(pl.Periodlist)-1)
FROM (SELECT CAST(c.Year AS varchar(4))+c.Quarter+',' AS [text()]
FROM #Calendar
WHERE ID =@ID
FOR XML PATH(''))pl(Periodlist)

SET @Sql='SELECT m.ItemID,COALESCE('+
REPLACE(@Periodlist,',',',0),COALESCE(') +
' FROM
(
SELECT CAST(c.Year AS varchar(4))+c.Quarter AS Period,
t.ItemID
t.Value
FROM #Calendar c
LEFT JOIN Table t
ON t.Year=c.Year
AND c.Quarter=t.Qtr
WHERE c.ID <=@ID )m
PIVOT (SUM(Value) FOR Period IN (['+ REPLACE(@Periodlist,',','],[') +']))p'

EXEC (@Sql)
Go to Top of Page

sql_2k
Starting Member

26 Posts

Posted - 2008-06-08 : 10:52:56
Thanks Visakh.You are surperb.

One small query - Though using the below query I am getting the results but without any column name for the fileds used in COALESCE functions.

I need to use the Isnull/COALESCE to get 0 where value is NULL but along with the field names.

Please advise.
Go to Top of Page
   

- Advertisement -