Starr Duskk
asked on
sql server count
I have a table full of schedules. Each schedule is owned by a client. I want to know how many schedules each client owns.
Please help. thanks!
Please help. thanks!
select distinct count(scheduleId), clientname from schedule
inner join client on client.clientid = schedule.clientid
group by scheduleid, clientname
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi,
Hope this query will help you if you have duplicate scheduleid then yo have to use Distinct in the count
Hope this query will help you if you have duplicate scheduleid then yo have to use Distinct in the count
select count(distinct scheduleId), clientname from schedule
inner join client on client.clientid = schedule.clientid
group by clientname
With a little tricky use of MIN you can have the advantage to group by the unique clientid and still show the clientname in the result:
If you don't need the name you don't even need a join and it all boild down to
Bye, Olaf.
select count(distinct scheduleId) as schedulecount, schedule.clientid,
MIN(schedule.clientname) as clientname
from schedule inner join client on client.clientid = schedule.clientid
group by schedule.clientid
Group By needs every single standing field to be grouped or aggregated, since all clientnames, so not grouping on clientname would cause an error, but since any clientid has just one clientname, MIN(clientname) is the same as clientname per clientid and satisfies the group by rules. If you don't need the name you don't even need a join and it all boild down to
select count(distinct scheduleId) as schedulecount, clientid from schedule
group by clientid
Bye, Olaf.
You only need the schedule table because you have a clientid value associated with any schedule:
select
clientid,
count(*) as schedule_count
from
schedule
group by
clientid
If you need the names then you can join:
select
clientid,
min(clientname) as clientname,
count(*) as schedule_count
from
schedule s
inner join client c
on c.clientid=s.clientid
group by
s.clientid
ASKER
thanks all!
GROUP BY produces rows that are unique for the combination of columns you nominate in that clause
SELECT DISTINCT - which is performed AFTER the group by - then checks if all the rows are unique, but they already are, so "select distinct" is just a waste of effort when you are doing group by too.
Chaau's query is absolutely correct just note you do not need to include schedule.clientid in the group or the select clauses, like this:
Open in new window
no points please