troubleshooting Question

Pivot SQL Query Question

Avatar of ALawrence007
ALawrence007 asked on
Microsoft SQL ServerMicrosoft SQL Server 2005SQL
6 Comments1 Solution437 ViewsLast Modified:
Hi,

I have the following query for my Pivot table. I "get" my results by month, but there is an issue with the results. The last 3 months results are exactly the same and I know by running other queries that is not the case. Can someone see what is wrong in my query? Also if there are better suggestions, PLEASE let me know.

Thanks
Declare @Month DateTime  
Set @Month = '12/1/2007'  
SELECT     datename(yy, @Month) As [Year], DepartMent.Name,
SUM(CASE WHEN ([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, 0, @Month), 0) AND DATEADD(month, DATEDIFF(month, 0, @Month) + 1, 0)) 
 
THEN [Transaction].Total ELSE 0 END) AS [Feb Total], 
 
SUM(CASE WHEN ([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, - 1, @Month), 0) AND DATEADD(month, DATEDIFF(month, - 1, @Month) + 1, 0)) 
 
THEN [Transaction].Total ELSE 0 END) AS [Jan Total], 
 
SUM(CASE WHEN ([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, - 2, @Month), 0) AND DATEADD(month, DATEDIFF(month, - 2, @Month) + 1, 0)) 
 
THEN [Transaction].Total ELSE 0 END) AS [Dec Total], 
 
SUM(CASE WHEN ([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, - 3, @Month), 0) AND DATEADD(month, DATEDIFF(month, - 3, @Month) + 1, 0)) 
 
THEN [Transaction].Total ELSE 0 END) 
                      AS [NOV Total]
FROM         [Transaction] INNER JOIN
TransactionEntry ON [Transaction].TransactionNumber = TransactionEntry.TransactionNumber INNER JOIN
Item ON TransactionEntry.ItemID = Item.ID INNER JOIN
Department ON Item.DepartmentID = Department.ID
 
WHERE       
([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, 0, @Month), 0) AND DATEADD(month, DATEDIFF(month, 0, @Month) + 1, 0)) OR
([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, - 1, @Month), 0) AND DATEADD(month, DATEDIFF(month, - 1, @Month) + 1, 0)) OR
([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, - 2, @Month), 0) AND DATEADD(month, DATEDIFF(month, - 2, @Month) + 1, 0)) OR
([Transaction].Time BETWEEN DATEADD(month, DATEDIFF(month, - 3, @Month), 0) AND DATEADD(month, DATEDIFF(month, - 3, @Month) + 1, 0))
Group By Department.Name
ASKER CERTIFIED SOLUTION
Mark Wills
Topic Advisor
Join our community to see this answer!
Unlock 1 Answer and 6 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros