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)
 Merging two pivot

Author  Topic 

CSK
Constraint Violating Yak Guru

489 Posts

Posted - 2007-12-12 : 16:34:35
Gurus,
I wrote two queries for process of budget for next year.
Those query is working fine. But i want to write it into one query. i ve tried for long time..
can anyone help me to merge the query..?


Select	location		  ,
[3] AS [Mar-08] ,
[4] AS [Apr-08] ,
[5] AS [May-08] ,
[6] AS [Jun-08] ,
[7] AS [Jul-08] ,
AS [Aug-08] ,
[9] AS [Sep-08] ,
[10] AS [Oct-08] ,
[11] AS [Nov-08] ,
[12] AS [Dec-08]

from
(
SELECT l.location as Location,Month, a.Cost ,Year(getdate())+1 as Year
FROM tblLFDMonth a
INNER JOIN tblSpace b ON a.SpaceID = b.SpaceID
INNER JOIN tlkpStatus c ON b.IsActive = c.StatusID
INNER JOIN tlkpComponent d ON a.ComponentID = d.ComponentID
INNER JOIN tlkpPmtStatus e ON a.PmtStatusID = e.PmtStatusID
INNER JOIN tbllocation l on a.locationid = l.locationid
where a.ComponentID =1
and c.PayRent = 1 and a.Year in (2008) and a.VariableExp = 0
And B.isactive =1
) AS A
PIVOT
(
max(Cost) for Month in ([3],[4],[5],[6],[7],,[9],[10],[11],[12])
) AS B
group by [3],[4],[5],[6],[7],,[9],[10],[11],[12],location
Order by 1

Select location ,
[1] AS [Jan-09] ,
[2] AS [Feb-09]

from
(
SELECT l.location as Location,Month, a.Cost ,Year(getdate())+1 as Year
FROM tblLFDMonth a
INNER JOIN tblSpace b ON a.SpaceID = b.SpaceID
INNER JOIN tlkpStatus c ON b.IsActive = c.StatusID
INNER JOIN tlkpComponent d ON a.ComponentID = d.ComponentID
INNER JOIN tlkpPmtStatus e ON a.PmtStatusID = e.PmtStatusID
INNER JOIN tbllocation l on a.locationid = l.locationid
where a.ComponentID =1
and c.PayRent = 1 and a.Year = 2009 and a.VariableExp = 0
And b.isactive = 1
) AS A
PIVOT
(
max(Cost) for Month in ([1],[2])
) AS B
group by [1],[2],location
Order by 1


Thanks
Krishna

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-12-12 : 16:42:18
Merge vertical or horizontal?



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

CSK
Constraint Violating Yak Guru

489 Posts

Posted - 2007-12-12 : 16:44:24
Vertical Merge.

Thanks
Krishna




Sorry Peso, Bit confuesed Horizontal Merge.
Thanks
Krishna
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-12-12 : 16:48:22
select coalesce(q1.location, q2.location) as location,
q1.col1, q1,col2, ..., q2.col1, q2.col2, ...
from (first query here) as q1
full join (second query here) as q2 on q2.location = q1.location



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

CSK
Constraint Violating Yak Guru

489 Posts

Posted - 2007-12-12 : 16:55:11
Its working, I got the exact output what i want

Thanks Peso
Krishna
Go to Top of Page
   

- Advertisement -