如何在SQL Server中检查count是否为1?

时间:2017-10-24 11:05:50

标签: sql-server count

我的Select查询条件为where,在这种情况下我必须检查我是否只获得1条记录。我已经尝试过如下所示的查询,但它没有成功。

SELECT *
FROM wsm_Certification_WorkersCompensation
WHERE
    (SELECT COUNT(*)
     FROM
         (SELECT TOP 1 WCS.ExpiryDate
          FROM wsm_Certification_WorkersCompensation AS WCS
          INNER JOIN [dbo].[wsm_Ref_State] AS ST ON WCS.StateID = ST.StateID
          WHERE WCS.CertificationID = 22653
            AND ExpiryDate >= GETDATE()
          ORDER BY ExpiryDate DESC) AS A = 1);

3 个答案:

答案 0 :(得分:2)

由于您选择TOP 1,然后检查计数是否为1,我很确定您可以用EXISTS替换您的逻辑:

SELECT  * 
FROM    wsm_Certification_WorkersCompensation
WHERE   EXISTS
        (   SELECT  1
            FROM    wsm_Certification_WorkersCompensation AS WCS 
                    INNER JOIN [dbo].[wsm_Ref_State] AS ST
                         ON WCS.StateID = ST.StateID
             WHERE  WCS.CertificationID = 22653 
             AND    ExpiryDate >= GETDATE()
        );

答案 1 :(得分:0)

您的查询语法错误。你也可以忽略内部查询中的order by子句

SELECT *
FROM wsm_Certification_WorkersCompensation
WHERE(
SELECT COUNT(*)
FROM
(
    SELECT TOP 1 WCS.ExpiryDate
    FROM wsm_Certification_WorkersCompensation AS WCS
         INNER JOIN [dbo].[wsm_Ref_State] AS ST ON WCS.StateID = ST.StateID
    WHERE WCS.CertificationID = 22653
          AND ExpiryDate >= GETDATE()
    ORDER BY ExpiryDate DESC
) AS A) = 1

答案 2 :(得分:0)

如果我理解你的要求是正确的。那可能是你想要的查询:

SELECT *
FROM wsm_Certification_WorkersCompensation
WHERE EXISTS (   SELECT TOP 1 1
                 FROM wsm_Certification_WorkersCompensation AS WCS
                 INNER JOIN dbo.wsm_Ref_State AS ST
                     ON WCS.StateID = ST.StateID
                 WHERE WCS.CertificationID = 22653
                 AND ExpiryDate >= GETDATE()
                 HAVING COUNT(*) = 1);

HAVING COUNT(*) = 1将检查内部查询中的匹配数是否为1,否则不会返回任何内容。