我有一张桌子User
和Company
。用户记录是公司记录的子记录,即用户表有一列parent_company_id
,表示用户所属的公司。
我想选择公司记录,以及相关用户记录中有多少公司有詹姆斯名字的计数,只有那些计数是> 0
这是我的第一个想法:
SELECT
c.name,
(SELECT
COUNT(*)
FROM [user] u
WHERE first_name = 'James'
AND u.parent_company_id = company_id)
AS james_count
FROM company c
WHERE james_count > 0;
这不能编译,因为外部查询不知道james_count
列别名。为什么不呢?
这样可行,但这不会慢,因为它会运行两个子查询吗?
SELECT
c.name,
(SELECT
COUNT(*)
FROM [user] u
WHERE first_name = 'James'
AND u.parent_company_id = company_id)
AS james_count
FROM company c
WHERE (SELECT
COUNT(*)
FROM [user] u
WHERE first_name = 'James'
AND u.parent_company_id = company_id)
> 0;
答案 0 :(得分:2)
有很多方法可以做到这一点。但一个是使用cross apply
:
select c.name, j.james_count
from company c cross apply
(select count(*) as james_count
from [user] u
where first_name = 'James' and u.parent_company_id = company_id
) j
where james_count > 0;
更自然的方法是简单地使用join
和group by
:
select c.name, count(*) as james_count
from company c join
[user] u
on u.parent_company_id = c.company_id and u.first_name = 'James'
group by c.name;
答案 1 :(得分:0)
您可以使用CTE。首先选择公司ID与詹姆斯的名字数量相对应。然后将该表与公司表联系起来。
WITH James (parent_company_id, james_count)
AS (SELECT parent_company_id,
COUNT(*)
FROM [User]
WHERE first_name = 'James'
GROUP BY parent_company_id)
SELECT c.*,
j.james_count AS no_of_companies_with_user_james
FROM [Company] AS c
INNER JOIN
[James] AS j
ON c.company_id = j.parent_company_id;