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.
Author |
Topic |
maunishq
Yak Posting Veteran
71 Posts |
Posted - 2014-07-01 : 04:02:15
|
Hi All,I'll describe my situation and problem first.I have two tables. Actual and Forecast.Actual table:Month KGMar 30Apr 40May 50Forecast table:Month KGApr 35May 30Jun 40Jul 50I want to generate a report which pulls the Actual data if exist otherwise the forecast data. So the output should be something like this:Mar Apr May | Jun Jul30 40 50 | 40 50So here Mar, Apr, May pulls data from Actual and Jun, Jul pulls data from Forecast.I wrote a query using union.SELECT SUM(....)FROM (SELECT ....FROM Actual tableWHERE Monthnum <= MONTH(Getdate())UNIONSELECT ....FROM Forecast tableWHERE Monthnum > MONTH(Getdate()))GROUP BY ....ORDER BY ....SSMS pulls correct data:Mar 30Apr 40May 50Jun 40Jul 50PROBLEM:On creating a dataset using the same query results in strange report:Mar Apr May Jun Jul30 40 50Mar Apr May Jun Jul- - - 40 50It seems they are grouping the Actual and Forecast in different rows which I do not want.I want them together.===========================================================Can anybody suggest me a better way to achieve the desired result?Thanks in anticipation.Rgds. |
|
stepson
Aged Yak Warrior
545 Posts |
Posted - 2014-07-01 : 05:00:09
|
[code]DECLARE @dtSysDateTime AS DATETIME2 = '2014-05-30';with ActualTableAS (SELECT 3 AS [MonthNum], 'Mar' AS [MONTH],30 AS KG UNION ALL SELECT 4,'Apr' , 40 UNION ALL SELECT 5,'May' , 50),ForecastTableAS (SELECT 4 AS [MonthNum],'Apr' AS [Month], 35 AS KG UNION ALL SELECT 5,'May' ,30 UNION ALL SELECT 6,'Jun' ,40 UNION ALL SELECT 7,'Jul' ,50),FinalTableAS( SELECT [Month] ,KG FROM ActualTable WHERE MonthNum<=Month(@dtSysDateTime) UNION ALL SELECT [Month] ,KG FROM ForecastTable WHERE MonthNum > Month(@dtSysDateTime))SELECT * FROM FinalTable AS FT PIVOT (SUM(KG) FOR [Month] IN ([Mar],[Apr],[May],[Jun],[Jul])) AS PV[/code]output:[code]Mar Apr May Jun Jul30 40 50 40 50[/code] sabinWeb MCP |
|
|
maunishq
Yak Posting Veteran
71 Posts |
Posted - 2014-07-02 : 10:28:19
|
Thanks Sabin.I'll check and see if this works for me.=======================Not an Expert, Just a learner.!_(M)_! |
|
|
maunishq
Yak Posting Veteran
71 Posts |
Posted - 2014-07-02 : 12:29:06
|
Thanks, It gave me a right direction. I didn't resolve the problem completely, but got some hands for sure. Thanks a lot.=======================Not an Expert, Just a learner.!_(M)_! |
|
|
|
|
|
|
|