Subquery aggregate function with SUM(CASE SUBQUERY)

只愿长相守 提交于 2019-12-11 17:08:35

问题


I'm getting an error while executing my query

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Code:

SELECT 
    S.id,
    SUM(CASE WHEN sc.coverage IN (SELECT number FROM ArrayOfIntegersFromString(@dynamicData)) THEN 1 ELSE 0 END) as sm
FROM 
    Storefronts s
    LEFT JOIN StorefrontCoverages sc ON s.id = sc.storefront
    LEFT JOIN Vendors v ON s.vendor = v.Id
WHERE
(
    v.active = 1
    AND
    s.approved = 1
    AND
    s.status = 1 
)
GROUP BY S.id
HAVING SUM(CASE WHEN sc.coverage IN (SELECT number FROM ArrayOfIntegersFromString(@dynamicData)) THEN 1 ELSE 0 END)  > 0
ORDER BY sm desc

SUM in SELECT is not that important as the one in HAVING, so if someone can help me out even without that SUM(...) in SELECT it would be helpful.


回答1:


I think it would be better to move the subquery to the from clause. Based on your logic, you are looking for joins, not left joins -- after all, the having clause is simply looking for any match.

I think the following query does what you want:

SELECT S.id, COUNT(dd.number) as sm
FROM Storefronts s JOIN
     StorefrontCoverages sc
     ON s.id = sc.storefront JOIN
     (SELECT number FROM ArrayOfIntegersFromString(@dynamicData)
     ) dd(number)
     ON sc.coverage = dd.number
WHERE s.approved = 1 AND s.status = 1 AND
      EXISTS (SELECT 1
              FROM Vendors v
              WHERE s.vendor = v.Id AND
                    v.active = 1
             )
GROUP BY S.id
ORDER BY sm desc;


来源:https://stackoverflow.com/questions/30121392/subquery-aggregate-function-with-sumcase-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!