0

Scenario:

I have 2 tables, Car Table, and Employee Table. Pretty simple tables, both tables however include a location code:

╔════════════════╗    ╔═══════════╗
║ Employee Table ║    ║ Car Table ║
╠════════════════╣    ╠═══════════╣
║ empID          ║    ║ CarID     ║
║ empName        ║    ║ CarName   ║
║ LocID          ║    ║ LocID     ║
╚════════════════╝    ╚═══════════╝

This is to represent Employees working at specific locations, and also shows which vehicles are in the respective locations.

What I am trying to display with this query is a count of each car, and employee GROUPED BY Location ID, for example:

Example of what I want

Every time I try a query, it always adds multiple location ids in the query, even though I want to group by it. Is this possible with one query?

1
  • It's generally frowned on to use external images for your sample output. That alone may account for the down vote somebody gave you. Beyond that it's also ideal that you give us some indication of what you've tried. Commented Mar 18, 2018 at 19:55

2 Answers 2

3
select e.LocId, EmpCount, CarCount
from
    (select LocId, count(*) as EmpCount from Employee group by LocId) as e
    inner join
    (select LocId, count(*) as CarCount from Car group by LocId) as c
        on c.LocId = e.LocId

Here's the general idea though I don't think that's perfect syntax for Access as I'm sure it must be missing a pair of parentheses somewhere. Since you have a many to many relationship you'll need to be able to collapse to a single row before joining them up.

I'm also assuming that every location will be represented by both an employee and a car. Perhaps you can get away with a left outer join if that's not completely true. As I believe that Access doesn't allow full outer join you'll need another workaround if you can't make assumptions along those lines.

It might also work to use count(distinct) but I think it'll be faster using the above approach if the tables are large.

select e.LocId, count(distinct e.EmpId) as EmpCount, count(distinct c.CarId) as CarCount
from Employee as e inner join Car as c on c.LocId = e.LocId
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

SELECT CASE WHEN (A.LocID IS NULL) THEN B.LocID ELSE A.LocID END
   LocID, Count(A.CarID), Count(B.empID) FROM Car A FULL OUTER JOIN
   Employee B ON A.LocID=B.LocID
GROUP BY A.LocID, B.LocID;

Comments

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.