SQL Server - getting duplicate rows with different queries

I am trying to get a count of child records (addresses) for each client. I have 2 questions, and I wonder if they are the same:

SELECT 
    a.AddressId,  c.CustomerID, COUNT(*) AS NumDuplicates 
FROM 
    Customers C
INNER JOIN 
    Addresses a ON c.AddressID = a.AddressID 
GROUP BY 
    c.CustomerID, a.AddressId 
ORDER BY 
    NumDuplicates DESC


SELECT 
    c.CustomerID,
    (SELECT COUNT(*) 
     FROM Addresses a 
     WHERE a.AddressID = c.AddressID) AS AddressCount
FROM 
    Customers c 
ORDER BY 
    AddressCount desc

If this is not the case, what's the difference? If they are effective?

+4
source share
1 answer

The two queries are different from each other, because the first returns only clients that have at least one match in the address table. The second returns all clients, even those who do not have a match, and AddressId- NULL.

Equivalent first request:

SELECT c.CustomerID, COUNT(a.AddressId) AS NumDuplicates
FROM Customers C LEFT JOIN
     Addresses a
     ON c.AddressID = a.AddressID 
GROUP BY c.CustomerID
ORDER BY NumDuplicates DESC;

, . , . , . SQL Server . , , .

+7

Source: https://habr.com/ru/post/1622934/


All Articles