简体   繁体   中英

SQL How many of a counted row is in another counted row?

I've been stuck on how to write a particular query for the following question:

How many employees are in how many businesses?

My end result should look like this:

EmployeeId Count BusinessId Count
1 23473423
2 56245764
3 834456

So there are 23473423 businesses connected to 1 employee, 23473423 businesses connected to 2 employees, etc.

I have a table with a list of items including EmployeeId and BusinessId. A BusinessId can connect to many EmployeeIds. So far I have the following code to get me employees per business

Select BusinessId,
    Count(EmployeeId) as EIdCount
From Table
Group by BusinessId

Which gets me me a list of BusinessIds and how many EmployeeIds are attached to it.

BusinessId EIdCount
23 2
24 5
25 1
26 3

But now I need to figure out how to further group it to where the BusinessId's can be grouped by the Grouped Counted Employee Ids. I've looked at subqueries, having by, and group but I am still at a loss how to progress this without running into an error. Thank you for your help in advance!

Not sure if this is what you want:

Select EIdCount, COUNT(BusinessId)
FROM (
  Select BusinessId,
      Count(EmployeeId) as EIdCount
  From Table
  Group by BusinessId) A
Group by EIdCount

Just use a subquery:

select
    EIdCount,count(BusinessId) as [BusinessId Count]
from
(
--your original query/start
    Select BusinessId,
        Count(EmployeeId) as EIdCount
    From Table
    Group by BusinessId
--your original query/end
)t
group by EIdCount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM