November 8, 2013 at 10:43 am
The Input data looks like that :
Date Productions
11/1/2013 500
11/30/2013 100
10/1/2013 10
10/20/2013 50
11/1/2012 1
11/20/2012 5
Current MonthPrevious MonthPrevious Year
500 10 1
100 50 5
I am trying to use Full outer join but some how its chaninging the grain .
Any ideas.
CREATE TABLE [dbo].[D](
[ProdDate] [smalldatetime] NULL,
[Productions] [varchar](20) NULL
) ON [PRIMARY]
November 8, 2013 at 11:06 am
Why are you storing productions as varchar? Do you expect non numeric values?
How do you compare results for previous month and previous year?
You should review your requirements for the report, it makes no sense if the amount of rows for current month, previous month and previous year don't match.
November 9, 2013 at 9:23 am
not sure from that explanation what exactly you want.
But a note on outer joins that they will be overridden if you filter on an "outer" table in the where clause. So for a full outer join, you either want all your filtering in the ON, or you want to define the outer join in a derived table/cte, then select from it with a where clause.
November 10, 2013 at 6:02 pm
I am not sure if this is what you're trying to do or not but I don't think you need a FULL JOIN for this:
CREATE TABLE #D(
[ProdDate] [smalldatetime] NULL,
[Productions] [varchar](20) NULL
);
INSERT INTO #D
SELECT '11/1/2013','500'
UNION ALL SELECT '11/20/2013','100' -- Changed so day matches others
UNION ALL SELECT '10/1/2013','10'
UNION ALL SELECT '10/20/2013','50'
UNION ALL SELECT '11/1/2012','1'
UNION ALL SELECT '11/20/2012','5';
SELECT
CurrentMonth=SUM(
CASE WHEN MONTH(ProdDate) = MONTH(GETDATE()) AND
YEAR(ProdDate) = YEAR(GETDATE())
THEN CAST(Productions AS INT) END)
,PriorMonth=SUM(
CASE WHEN MONTH(ProdDate) = MONTH(GETDATE())-1 AND
YEAR(ProdDate) = YEAR(GETDATE())
THEN CAST(Productions AS INT) END)
,PriorYear=SUM(
CASE WHEN MONTH(ProdDate) = MONTH(GETDATE()) AND
YEAR(ProdDate) = YEAR(GETDATE())-1
THEN CAST(Productions AS INT) END)
FROM #D
GROUP BY DAY(ProdDate)
GO
DROP TABLE #D;
Note that I changed one row of your sample data (see comment).
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply