0

I am trying to create a query that provides me with the total number of Agents (AgentID) for each OfficeID. If someone could please guide me in the right direction, also if there are resources that give you a bunch of examples of different types of queries that would be useful for the future!

My issue right now is the syntax. I'm not sure where things need to go in order to get the desired output above.

Here's what I have as of now:

Tables OFFICE and AGENT:

CREATE TABLE OFFICE
(
     OfficeID NVARCHAR(5) UNIQUE,
     OfficeAddress NVARCHAR(18) NOT NULL,
     PRIMARY KEY(OfficeID)
)
GO

CREATE TABLE AGENT
(
     AgentID NVARCHAR(8) UNIQUE,
     OfficeID NVARCHAR(5) NOT NULL,
     AgentType NVARCHAR(9) NOT NULL,
     AgentFName NVARCHAR(10) NOT NULL,
     PRIMARY KEY (AgentId),
     FOREIGN KEY (OfficeID) REFERENCES OFFICE
             ON DELETE CASCADE
             ON UPDATE CASCADE
)
GO

Query:

SELECT
    OFFICE.OfficeID
FROM 
    OFFICE,
    (SELECT COUNT(AgentID)
     FROM AGENT, OFFICE 
     WHERE OFFICE.OfficeID = AGENT.OfficeID
     GROUP BY AGENT.OfficeID) 
ORDER BY 
    OFFICE.OfficeID
1
  • Bad habits to kick : using old-style JOINs - that old-style comma-separated list of tables style was replaced with the proper ANSI JOIN syntax in the ANSI-92 SQL Standard (more than 25 years ago) and its use is discouraged Commented Dec 5, 2018 at 6:11

3 Answers 3

2

I'd do this with a JOIN and GROUP BY, no nesting required or wanted:

SELECT o.OfficeID, COUNT(a.AgentID) NumberOfAgents
FROM Office o
LEFT JOIN Agents a ON a.OfficeID = o.OfficeID
GROUP BY o.OfficeID
Sign up to request clarification or add additional context in comments.

Comments

0

Something like this (your desired output appears to be missing):

SELECT O.OfficeID
  , (
    SELECT COUNT(*)
    FROM AGENT A
    WHERE A.OfficeID = O.OfficeID
)
FROM OFFICE O
ORDER BY O.OfficeID

Note the use of the table alias which is a recommended practice to keep your queries concise.

Comments

0

You need to be specific with what you want as per what I think no complex query is required in your case. For example you can get your desired output from the below query

select officeid, count(1) as NoofAgents
from Agents 
group by officeid

SQL can give you your desired way in a lot way and you can choose them based on the optimized solution.

1 Comment

I did think about this before posting my answer, but I decided to keep the join in case of an office with no agents, where the OP might still want a 0 result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.