Using the COUNT function in SQL

前端 未结 5 1041
猫巷女王i
猫巷女王i 2021-01-25 00:24

First and Foremost, this is part of an assignment.

I am trying to use the COUNT function as part of a query in relation to the Northwind database. The query should retur

相关标签:
5条回答
  • 2021-01-25 01:04

    When using aggregate functions like COUNT(), all columns have to be part of aggregate functions. The GROUP BY statement should solve your problem. http://www.w3schools.com/sql/sql_groupby.asp

    0 讨论(0)
  • 2021-01-25 01:06

    You need a group by clause, which will allow you to split your result in to groups, and perform the aggregate function (count, in this case), per group:

    SELECT   Customers.CustomerID, Customers.CompanyName, COUNT(*)
    FROM     Orders, Customers
    WHERE    Customers.CustomerID = Orders.CustomerID;
    GROUP BY Customers.CustomerID, Customers.CompanyName
    

    Note: Although this is not part of the question, it's recommended to use explicit joins instead of the deprecated implicit join syntax you're using. In this case, the query would look like:

    SELECT   Customers.CustomerID, Customers.CompanyName, COUNT(*)
    FROM     Orders
    JOIN     Customers ON Customers.CustomerID = Orders.CustomerID;
    GROUP BY Customers.CustomerID, Customers.CompanyName
    
    0 讨论(0)
  • 2021-01-25 01:07

    The below query should work.

        SELECT Customers.CustomerID, Customers.CompanyName, COUNT(*)
        FROM Orders, Customers
        WHERE Customers.CustomerID = Orders.CustomerID group by Orders.CustomerID
    
    0 讨论(0)
  • 2021-01-25 01:21

    First, if you are learning SQL, you should learn proper explicit join syntax. Simple rule: never use a comma in the from clause.

    Second, your query should use group by instead of distinct. In fact, it is more important to learn group by than to learn distinct, because you can generally write select distinct using group by.

    So, where you are heading is:

    SELECT c.CustomerID, c.CompanyName, COUNT(c.CustomerID)
    FROM Orders o JOIN
         Customers c
         ON c.CustomerID = o.CustomerID
    GROUP BY c.CustomerID, c.CompanyName;
    
    0 讨论(0)
  • 2021-01-25 01:22

    You are missing the group by clause. Your query should look like this

    select CustomerID, Customers.CompanyName, count(CustomerID)
    from Orders JOIN Customers using(CustomerID)
    group by CustomerID;
    

    Notice that I used the Join syntax which is more concise when joining tables.

    0 讨论(0)
提交回复
热议问题