简体   繁体   中英

Returning count using multiple subqueries

Forgive my ignorance, but sql-server is not my strong suit. I'm trying to retrieve the count of rows from two mapping tables using subqueries (correlated subqueries?). If I remove one subquery, things work fine, but if I include both subqueries, I'm not getting the expected number of rows back.

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
        )

If I'm not mistaken about what you want to achieve here, then this can be achieved by using grouping with COUNT and DISTINCT operators:

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

It is hard to tell if result is correct without seeing your data and expected result. If the above does not work, try removing DISTINCT operators and see if you get the results that you need.

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