Monday, April 14, 2008

Re: What is wrong with this query?

I received a lot of replies about this query but one man was dead on! There is a reason he is known as the "Babe Jee" of Databases! Abdullah Idris cracked this query in 60 secs flat!

Syntactically, there is nothing wrong with this query however it is very unefficient and the logic does not make any sense. Here is how this query should be written;

SELECT
C.CustomerID, C.CustomerName,
C.CustomerType, C.Address1, C.City,
C.State, S.TotalSales
FROM
Customers C
INNER JOIN
(SELECT
CustomerID, SUM(Sales) as TotalSales
FROM
Sales
GROUP BY
CustomerID) S
ON
C.CustomerID = S.CustomerID

2 comments:

M. Adil Amin said...

we can write Query like this. This Query should be Efficient.

SELECT
CustomerID, CustomerName,
CustomerType, C.Address1, C.City,
State, SUM(Sales) as TotalSales
FROM
Customers C
GROUP BY CustomerID, CustomerName,
CustomerType, Address1, City,
State

trg tech said...

Adil,
You are overlooking a key factor here. The sales column does not exist in the Customers but in fact the sales table.

That is why we need to join the two tables