How I will properly do this:
Customer
CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
Order
OrderID, Ord
A little bit different version (from that Gordon Linoff suggests):
select
cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
from Customer c
join (
select
count(OrderID) cnt, CusID
from Order o
group by
CusID
) o on
c.CusID = o.CusID
order by
c.CusID // ordering by OrderID and Order is out of logic :)
Why do I need to add those columns in the Group By Clause?
Because you are saying you need to group the results and give one result per ID. This leaves you with two choices.
1) Getting the count with all details at the customer level, which is what you would want in your example.
Select Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
From Customer c
Inner join
Order o
On c.CusID = o.CusID
Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd;
2) Or in case the other columns are some numbers (say salaries in a department) or so, every column not in the group by should have an aggregate function.
select dept_id, sum(salary), max(salary), min(salary)
from dept
group by dept_id;
When you want one row per your grouped column, you need to specify how to aggregate the other columns.
I also find first answer to be the best, but in SQL2005 CTEs came into existence and they can help obtain better readability:
;with order_cte as (
select count(OrderID) cnt, CusID
from Order o
group by CusID
)
select cnt, c.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
from Customer c
join order_cte o on c.CusID = o.CusID
order by c.CusID
Just include them in the group by
clause:
Select Count(OrderID), o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd
From Customer c
Inner join
Order o
On c.CusID = o.CusID
Group By o.CusID, CusLname, CusFname, CusMname, CusAddress, CusEmailAdd;