将变量设置为另一个查询作为源的查询计数

时间:2013-11-15 19:29:40

标签: sql

我在单词FROM附近的语法不正确。似乎找不到像查询检索子查询计数这样的其他内容,有关如何实现这一点的任何想法?

SET 
    @ctA = COUNT(*) 
FROM 
    (SELECT 
         theFN, theIN, theLN, theALY 
     FROM 
         aDT
     GROUP BY 
         theFN, theIN, theLN, theALY
     HAVING 
         theFN = @pF AND theIN = @pI AND theLN = @pL AND theALY = @pLY
    )

2 个答案:

答案 0 :(得分:1)

尝试

select @ctA = COUNT(*) 
FROM 
(
   SELECT theFN, theIN, theLN, theALY 
   FROM aDT
   GROUP BY theFN, theIN, theLN, theALY
   HAVING theFN = @pF and theIN = @pI 
   and theLN = @pL and theALY = @pLY
) x

答案 1 :(得分:1)

构建此类查询的方法有很多种;这是一个:

 SELECT @ctA = COUNT(*) FROM aDT
           GROUP BY theFN, theIN, theLN, theALY
           HAVING theFN = @pF and theIN = @pI and 
           theLN = @pL and theALY = @pLY

...虽然您可能希望使用WHERE而不是HAVING进行过滤。实际上,引擎必须进行所有分组然后过滤;如果您使用WHERE子句然后分组,它将首先过滤然后进行分组。分组记录较少。

ETA:marc_s提出了一个很好的观点;我重写了查询