问题
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 join
s, not left join
s -- 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