Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

2 joined crosstabbed tables creating triplicates

$
0
0

What I am attempting:

1.Cross-tab 2 tables that contain Monthly Sales (the original text file has a column called month and lists by month. Theend user needs to view by month going across )

2. Join Both Tables. One table is 2013 sales and the other is 2014 Sales. Same Column names, same data types

3. The columns that should been are the columns identifying the dealer, Jan-Dec of current year regardless of what thecurrent month is, sum Current Year Total curernt point in time YTD, sum last current point of time in year. So for exampleright now I would only like to see Jan-Mar both 2014 and 2013. For the current year, the remainder of the monthsshould all have 0's.

What I have accomplished:

I can create 2 separate queries that accomplishes the task for each year. For previous years(2013) I use a where clause to only include Jan Feb and Mar. When I join the two tables(any type of Join) the sales figures get tripled.

The code I have posted below:

I am including my code below to join the two tables and only use jan-mar. What am I missing?

SELECT     substring([2014].Dealer,18,50)AS [Dealer Name],substring([2014].Dealer,9,1)AS [District],substring([2014].Dealer,11,6)AS [Dealer Code],
SUM(CASE WHEN [2014].[Transaction Sales Month] = 1 THEN [2014].[Sales Count] ELSE 0 END) AS Jan, 
            SUM(CASE WHEN [2014].[Transaction Sales Month] = 2 THEN [2014].[Sales Count] ELSE 0 END) AS Feb, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 3 THEN [2014].[Sales Count] ELSE 0 END) AS Mar, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 4 THEN [2014].[Sales Count] ELSE 0 END) AS Apr, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 5 THEN [2014].[Sales Count] ELSE 0 END) AS May, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 6 THEN [2014].[Sales Count] ELSE 0 END) AS Jun, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 7 THEN [2014].[Sales Count] ELSE 0 END) AS Jul, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 8 THEN [2014].[Sales Count] ELSE 0 END) AS Aug, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 9 THEN [2014].[Sales Count] ELSE 0 END) AS Sep, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 10 THEN [2014].[Sales Count] ELSE 0 END) AS Oct, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 11 THEN [2014].[Sales Count] ELSE 0 END) AS Nov, 
SUM(CASE WHEN [2014].[Transaction Sales Month] = 12 THEN [2014].[Sales Count] ELSE 0 END) AS [Dec],
SUM([2014].[Sales Count]) AS [2014 Total]

FROM [2014] right outer join [2013] on
[2014].Dealer=[2013].Dealer
WHERE [2014].[Transaction Sales Month] IN ('1','2','3')
GROUP BY substring([2014].Dealer,18,50),substring([2014].Dealer,9,1),substring([2014].Dealer,11,6)


Viewing all articles
Browse latest Browse all 23857

Trending Articles