Help with GROUP BY clause
need your 开发者_运维知识库help with GROUP BY
clause.
I have two tables: Managers and Clients (I simplified it for a question).
Managers:
managerId int PK,
ManagerName nvarchar(50)
and
Clients:
ClientId int,
ClientName nvarchar(50),
ManagerId int, WhenAdded datetime
I store managers list in Managers table. Each client from Clients table has a corresponding manager.
I want a sql query which returns following table:
ManagerName nvarchar(50),
NumberOfClients int
My problem is:
if manager doesn't have a client(s). Sql query doesn't include ManagerName
in resulting table.
I tried this query:
SELECT M.ManagerName, COUNT(*)
FROM
Clients AS C left join Managers AS M
ON
C.ManagerId = M.ManagerId
GROUP BY
M.ManagerName
Second question
Same as a first question, but if I want to add a where
clause to the WhenAdded
field in Clients). Query must return ManagerName
and NumberOfClients
even if NumberOfClients=0
.
You can use this:
SELECT ManagerName, (SELECT Count(ClientID) FROM Clients C WHERE
C.ManagerID=M.ManagerID) As NumberOfClients FROM Managers M;
or this:
SELECT ManagerName, Count(C.ClientID) As NumberOfClients FROM Managers M
LEFT JOIN Clients C ON M.ManagerID=C.ManagerID GROUP BY M.ManagerID,
M.ManagerName;
The problem with your query is that you're using Clients table as basic table.
For the second question you can use this:
SELECT ManagerName, (SELECT Count(ClientID) FROM Clients C WHERE
WhenAdded<DATEADD(day, 1, GETDATE()) AND M.ManagerID=C.ManagerID) As
NumberOfClients FROM Managers M;
This should work. Not very optimized though!
select m.ManagerName , count(c.ManagerId) from Managers m, Clients c where
m.ManagerId = c.ManagerId group by c.ManagerId
精彩评论