我有一个存储过程,其中我试图选择表Table 1的所有列。还有另一个表使用Table1主键作为外键。我想用此选择来计数此外键表中的记录数:

SELECT *, count(*) VacancyCount
    FROM Table1 hc
    LEFT JOIN Table2 hv
    on hc.CompanyID = hv.CompanyID
    WHERE hc.Deleted = 0
    group by hc.CompanyID
    ORDER BY NameLang1

但它给出了错误:



请建议如何解决此问题?

最佳答案

请尝试:

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

使用新列进行订购
select * from(
    select
        *,
        CONVERT(NVARCHAR(100), (select COUNT(*) from Table2 hv where hv.CompanyID=hc.CompanyID)) VacancyCount
    from Table1 hc
    where
        hc.Deleted = 0
)x
Order by CASE WHEN @OrderByParam = 1 THEN NameLang1 ELSE VacancyCount END

提供的列NameLang1VacancyCount具有相同的数据类型。

09-26 17:29