SQL Server 2012 Express How do I pull information from one column and compare it to another with an expression restriction

StackOverflow https://stackoverflow.com/questions/22998717

Question

Sorry, I'm trying to word this correctly. Essentially what I'm trying is compare one column from a table to another column from a table to check and see how many rows are in that second column. I'm using the Northwind sample database and the question is as follows.

List all customers (include CustomerId and Company Name) who have placed less than 5 orders.

  • Include those customers who have placed 0 orders. Name the count field "OrderCount."
  • Order by number of placed orders in reverse order.

I'm absolutely stuck on this.

Was it helpful?

Solution

This might have the names a little off.

    SELECT c.CustomerId, c.[Company Name], ISNULL(OrderSum.OrderCount,0) AS OrderCount
    FROM Customers c
    LEFT JOIN (SELECT CustomerId, Count(1) OrderCount
               FROM Orders
               GROUP BY CustomerId) OrderSum
    ON c.CustomerId = OrderSum.CustomerId
    WHERE ISNULL(OrderSum.Cnt, 0) < 6
    ORDER BY 2

OTHER TIPS

Although JBrooks answer looks perfectly fine, I would have gone for this

SELECT c.CustomerId, c.[Company Name], COUNT(o.Customer_id) as OrderCount
    FROM Customer c
    LEFT JOIN Orders o
           ON o.CustomerId = c.CustomerId
    GROUP BY c.CustomerId, c.[Company Name]
    HAVING COUNT(o.Customer_id) < 6
    ORDER BY 2

And I'm now wondering which one is more efficient ... I'll install Northwind tomorrow if I find the time...

UPDATE: Installed Northwind and tried both JBrooks and my version. Seems they are pretty much equivalent although it's dangerous to draw conclusions on such a small dataset off cousre.

QueryPlan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top