troubleshooting Question

SQL Question Two Left Joins, Aggregates

Avatar of coldchillin
coldchillin asked on
Microsoft SQL Server 2008
5 Comments1 Solution191 ViewsLast Modified:
I have a transaction table with CustomerId, ItemId, DollarAmt, QTY, and TransDate

I need to join to Customer table, Item table. Here's my problem:

I need to get This Year and Last Year data in the same record.

 
SELECT CustomerId, ItemId, SUM(ThisYear.DollarAmt), SUM(ThisYear.QTY), SUM(LastYear.DollarAmt), SUM(LastYear.DollarAmt)
FROM Customer c
LEFT JOIN (
SELECT DollarAmt,QTY,CustomerId
FROM Sales s
JOIN Customer c ON c.CustomerId = s.SalesId
WHERE Date = {date logic}
) AS ThisYear ON ThisYear.CustomerId = c.CustomerId
LEFT JOIN (
SELECT DollarAmt,QTY,CustomerId
FROM Sales s
JOIN Customer c ON c.CustomerId = s.SalesId
WHERE Date = {date logic}
) AS LastYear ON LastYear .CustomerId = c.CustomerId
GROUP BY CustomerId, ItemId

This should group all the sales data by Customer, however, I don't believe it's correctly placing the same items this year and last year item.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 5 Comments.
Join the Community
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 5 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