简体   繁体   English

在SQL Server中从子表中获取计数大于0的记录

[英]get records from child table having count greater than 0 in sql server

I have a query below. 我在下面有一个查询。

select 
    *,
    (select COUNT(*) from Table2 hv where hv.CompanyID=hc.CompanyID) VacancyCount
from Table1 hc
where
    hc.Deleted = 0
order by hc.NameLang1, VacancyCount desc

It gives me the right records always.I just want to add one more clause here is that select only those records from Table1 which is having atleast one record in Table2.Currently it returns all records which is having 0 records in Table2. 它总是给我正确的记录。我只想在这里添加一个子句,即仅从Table1中选择那些在Table2中至少有一个记录的记录。当前它返回所有在Table2中具有0个记录的记录。

Please help me to solve this problem. 请帮我解决这个问题。

Try This 尝试这个

SELECT 
    *,
    (SELECT COUNT(*) FROM Table2 hv WHERE hv.CompanyID=hc.CompanyID) VacancyCount
FROM Table1 hc
WHERE EXISTS (SELECT hv.CompanyID FROM Table2 hv WHERE hv.CompanyID=hc.CompanyID)
   AND hc.Deleted = 0
ORDER BY hc.NameLang1, VacancyCount DESC;

For More know about EXISTS http://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html 有关EXISTS的更多信息,请访问http://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

If You would like to select only records from Table1 which is having atleast one record in Table2 maybe You can try to using Inner Join. 如果您只想从Table1中选择在Table2中至少有一条记录的记录,则可以尝试使用内部联接。

select 
    hc.*,
    COUNT(.....some column in hv to be count....) as VacancyCount 
from 
  Table1 hc
  INNER JOIN Table2 hv ON hc.CompanyID ON hv.CompanyID
where
    hc.Deleted = 0
GROUP BY (....group all your hc column here....)
order by hc.NameLang1, VacancyCount desc

This will return all data in table1 which is having atleast one record in Table2. 这将返回表1中在表2中至少有一条记录的所有数据。 If there's any rows in table1 which doesn't have record in Table2 then that rows will not shown. 如果表1中有任何行在表2中没有记录,则该行将不会显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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