SQL Server difference between two queries?

72 views Asked by At

This is my table:

enter image description here

I have a problem I don't understand the difference between the following two queries:

Query #1:

SELECT 
    productID,
    SUM(soldQty)
FROM
    Sales
WHERE
    soldQty <> 0
GROUP BY  
    ProductID

Query #2:

SELECT
    productID,
    SUM(soldQty)
FROM
    Sales
GROUP BY 
    ProductID
HAVING
    SUM(soldQty) <> 0

Which productID's will result in the queries? Isn't it the same?

2

There are 2 answers

0
Thom A On

The queries are not the same. The first query will SUM rows where the value of soldQty is not equal to 0.

The second query, however, will return rows where the SUM of the values in soldQty do not total 0. As a result if the SUM of the values comes to 0, such as 10, -4 and -6 those rows would be omitted. This would not be the case for the first query.

SELECT MyColumn,
       SUM(IntColumn) AS TotalIntColumn
FROM (VALUES(1,0),
            (1,2),
            (1,5),
            (1,0),
            (1,-2),
            (2,10),
            (2,-4),
            (2,-6),
            (2,0),
            (3,0))V(MyColumn,IntColumn)
WHERE IntColumn <> 0
GROUP BY MyColumn;

SELECT MyColumn,
       SUM(IntColumn) AS TotalIntColumn
FROM (VALUES(1,0),
            (1,2),
            (1,5),
            (1,0),
            (1,-2),
            (2,10),
            (2,-4),
            (2,-6),
            (2,0),
            (3,0))V(MyColumn,IntColumn)
GROUP BY MyColumn
HAVING SUM(IntColumn) <> 0;

Notice that 2 is returned in the first dataset, with a value of 0 for TotalIntColumn, but it is not returned in the second. Neither result set return a row with a value of 3 for MyColumn as IntColumn only contains the value 0.

0
Ross Bush On

Query 1 will omit all records, regardless of productid, having a soldQty <> 0

Query 2 will omit all records associated with all products having a cumulative sum soldQty <> 0