使用多个子查询返回计数

时间:2016-07-21 17:49:33

标签: sql sql-server subquery

原谅我的无知,但是sql-server并不是我的强项。我正在尝试使用子查询(相关子查询?)从两个映射表中检索行数。如果我删除一个子查询,一切正常,但如果我包含两个子查询,我没有得到预期的行数。

SELECT 
    a.id,
    a.name,
    al_1.locationid as LocationCount,
    af_1.FuncAreaId as FuncAreaCount

FROM
    application as a inner join
    applicationlocation as al_1 on a.id = al_1.appid inner join
    applicationfuncarea as af_1 on a.id = af_1.AppId
WHERE
    al_1.locationid in
        (
            SELECT count(locationid)
            FROM applicationlocation as al_2
            WHERE al_2.appid = al_1.appid
        )
AND 
    af_1.funcareaid in 
        (
            SELECT count(funcareaid)
            FROM applicationfuncarea as af_2
            WHERE af_2.appid = af_1.appid
        )

1 个答案:

答案 0 :(得分:1)

如果我没有弄错你想要在这里实现什么,那么可以通过使用COUNTDISTINCT运算符进行分组来实现这一目标:

SELECT 
    a.id,
    a.name,
    COUNT(DISTINCT al_1.locationid) as LocationCount,
    COUNT(DISTINCT af_1.FuncAreaId) as FuncAreaCount
FROM
    application as a inner join
    applicationlocation as al_1 on a.id = al_1.appid inner join
    applicationfuncarea as af_1 on a.id = af_1.AppId
GROUP BY a.id, a.name

如果没有看到您的数据和预期结果,很难判断结果是否正确。如果上述操作无效,请尝试删除DISTINCT运算符,看看是否得到了所需的结果。