How to get all Customers records in Northwind (with and without orders) - sql-server-2005

With this code I will get only customers records with total of orders more than zero, but I need get the customers with zero total of orders also.
How to get all Customers record in Northwind with and without orders?
thanks for the help.

Changing INNER JOIN to LEFT JOIN will return customers who do not have orders.
SELECT Customers.CustomerID,
Customers.CompanyName,
COUNT(Orders.OrderID) AS Total
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.CustomerID,
Customers.CompanyName
This query returns all customers (91 in the Northwind DB) and the total displays 0 for those who do not have orders.
Is this what you were after?

Related

Beginner: LEFT JOIN not doing what it should?

I'm having trouble with a really simple left join statement that's driving me nuts
I wanted to count the numbers of orders from each customer, that's fine, but I want to display the name, and I'm joining with the customers table and trying to select the name and it says that CustomerName is not part of an aggregate function, it's really weird.
SELECT Customers.CustomerName as 'Name',
COUNT(*) AS 'Order Count'
FROM Orders
LEFT JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
GROUP BY Customers.CustomerID
Thanks for any tips.
You need to count the rows from the orders table, and the left join should be in the other direction:
SELECT c.customerid,
c.CustomerName as "Name",
COUNT(o.customerid) AS "Order Count"
FROM Customers c
LEFT JOIN Orders o ON o.CustomerID = cs.CustomerID
GROUP BY c.CustomerID, c.customername;
count() will ignore NULL values that come into the result due to the outer join so it will count the number of orders for each customers. Customers without orders will be show with a zero count.
Include CustomerName in Group BY instead of CustomerID
SELECT Customers.CustomerName as 'Name', COUNT(*) AS 'Order Count'
FROM Orders LEFT JOIN Customers ON Orders.CustomerID = Customers.CustomerID
GROUP BY Customers.CustomerName
If you are using SQL Server then try using OVER() without Group BY
SELECT Customers.CustomerName as 'Name', COUNT(*) OVER (PARTITION BY Customers.CustomerName ORDER BY Customers.CustomerName)AS 'Order Count'
FROM Orders LEFT JOIN Customers ON Orders.CustomerID = Customers.CustomerID
Modify as below. column used in group by clause should be in column queried in select clause
SELECT Customers.CustomerName as 'Name',
COUNT(*) AS 'Order Count'
FROM Orders
LEFT JOIN Customers
ON Orders.CustomerID = Customers.CustomerID
GROUP BY Customers.CustomerName
I have just reordered your query,please try this it will definitely work for you.
SELECT Customers.CustomerName as 'Name',
COUNT(*) AS 'Order Count'
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
GROUP BY Customers.CustomerID
A simple approach to get all the columns in the customers table is to use a correlated subquery:
select c.*, -- or whatever columns you want
(select count(*)
from orders o
where o.CustomerID = c.CustomerID
) as order_count
from customers c;
Because this avoids the outer GROUP BY, this also has the advantage of having better performance in most databases, particularly with an index on orders(CustomerId). Plus, it returns 0 if the customer has no orders. And, it allows you to choose any or all of the columns from Customers.
The correct way to get the counts you want is to count a column from Orders:
SELECT c.CustomerName, c.CustomerID,
COUNT(o.CustomerId) AS Order_Count
FROM Customers c LEFT JOIN
Orders o
ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerID, c.CustomerName;
Notes:
The Customers table goes first in the LEFT JOIN because presumably you want all rows in Customers.
Table aliases make the query easier to write and to read.
Do not use single quotes for column aliases, even if your database supports it. The best method is to choose aliases that do not need to be supported.
Include the CustomerId in the logic, just in case two customers have the same name.
Count a column from Orders so you get a count of 0 for customers with no orders.

SQL confusion with the groupby function

SELECT customers.CompanyName,
customers.ContactName,
customers.phone,
customers.country,
SUM(orders.Freight) AS Total_Freight
FROM CUSTOMERS INNER JOIN ORDERS
ON customers.CustomerID = ORDERS.customerID
WHERE orders.orderDate BETWEEN '1993-07-01' AND '1993-08-31'
GROUP BY Orders.orderID, customers.CustomerID
ORDER BY customers.companyName
Above is my code, but I am getting error
Column 'CUSTOMERS.CompanyName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Why is that? Where did I go wrong?
The database
THis is the question.
List the company name, contact name, phone number, and country from the Customers table, and the sum of the freight from the Orders table where the order date is between July 1, 1993 and August 31, 1993. Order the result set by the company name. The query should produce the result set listed below.
The result format is too messy, I doubt it will be helpful to anyone.
use all the selection column in group by also as you used aggregate function
SELECT customers.CompanyName,
customers.ContactName,
customers.phone,
customers.country,
SUM(orders.Freight) AS Total_Freight
FROM CUSTOMERS INNER JOIN ORDERS
ON customers.CustomerID = ORDERS.customerID
WHERE orders.orderDate BETWEEN '1993-07-01' AND '1993-08-31'
GROUP BY customers.CompanyName,
customers.ContactName,
customers.phone,
customers.country
ORDER BY customers.companyName

SQL - cannot perform distinct count when joining two tables

I have two tables: Customers and Orders. I do a left join of Customers and Orders on CustomerID column which is primary key in Customers and foreign key in Orders.
When I list CustomerID after joining, I get the list as expected.
When I count the number of CustomerID, again I get the number of record I am expecting.
When I use distinct count for CustomerID, i get an error.
1.
select Customers.CustomerID as list
from Customers left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;
2.
select count(Customers.CustomerID) as numRecord
from Customers left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;
3.
select count(distinct (Customers.CustomerID)) as numRecord
from Customers left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;
I cannot understand where is the error. Any help would be appreciated.
The error:
Error in SQL:
Syntax error (missing operator) in query expression 'count(distinct Customers.CustomerID)'.
You don't need the () around Customers.CustomerID in count(distinct ..)
select count(distinct Customers.CustomerID) as numRecord
from Customers
left join Orders on Customers.CustomerID = Orders.CustomerID
where Customers.CustomerID = 4;

Calculate Amount of Product from Northwind

How can I calculate the total amount for product after discount of each EmployeeId in Northwind database of SQL Server?
The tables used from Northwind database are:
Employees
Order details
Products
If you are calculating amount for each EmployeeId
you have to use one more table for join along with these tables
Orders
Products
Employees
Order Details
and your query should be
select O.EmployeeID,OD.ProductID,Sum(OD.UnitPrice*Quantity *(1-Discount)) as TotalAmount from Orders as o
inner join [Order Details] as OD on OD.OrderID=o.OrderID
inner join Products as p on p.ProductID=OD.ProductID
group by OD.ProductID,o.EmployeeID
order by OD.ProductID
Write the code (Country, City, TotalCustomer) to show how many customers there are in each city in the country from the Northwind database

Using DISTINCT in SQL Query

How do i use DISTINCT command in a SQL query to show the supplier id, company name, and the number of distinct products from that supplier that were ordered prior to a specific date? I ran the code in Access but it doesn't translate over to SQL efficiently. The table appears.
[Supplier ID Company Name Product Name Order Date
1 Exotic Liquids Chang 17-Aug-94
1 Exotic Liquids Chang 22-Nov-94
1 Exotic Liquids Aniseed Syrup 26-Sep-94]
The code I have so far is the following. Where I get confused is where to put the DISTINCT statement. Should it be immediately after the Select? Should it go in Parentheses in addition to the SELECT? Excuse my lack of knowledge on this subject in advance.
SELECT Suppliers.SupplierID, Customers.CompanyName, Products.ProductName,
Orders.OrderDate
FROM Suppliers INNER JOIN
Products ON Suppliers.SupplierID = Products.SupplierID CROSS JOIN
Customers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate <='1/1/1999'
ORDER BY Suppliers.SupplierID
You can either distinct by all columns selected :
SELECT DISTINCT
Suppliers.SupplierID, Customers.CompanyName, Products.ProductName,
Orders.OrderDate
FROM
Suppliers INNER JOIN
Products ON Suppliers.SupplierID = Products.SupplierID CROSS JOIN
Customers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID
WHERE
Orders.OrderDate <='1/1/1999'
ORDER BY
Suppliers.SupplierID
or use group by instead if you need to distinct only by SupplierID. DISTINCT is not a function, hence DISTINCT(Suppliers.SupplierID) means the same as simply put DISTINCT word after SELECT in this case (see the 2nd reference below).
For Reference :
http://blog.sqlauthority.com/2007/12/20/sql-server-distinct-keyword-usage-and-common-discussion/
http://weblogs.sqlteam.com/jeffs/archive/2007/10/12/sql-distinct-group-by.aspx
I'm pretty sure it's this:
SELECT DISTINCT(Suppliers.SupplierID), Customers.CompanyName, Products.ProductName,Orders.OrderDate
FROM Suppliers INNER JOIN
Products ON Suppliers.SupplierID = Products.SupplierID CROSS JOIN
Customers INNER JOIN
Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderDate <='1/1/1999'
ORDER BY Suppliers.SupplierID