我有一个SQL查询,我只想返回1行。如果有多行,我想返回null。

我想我可以用

SELECT whatever FROM MyTable
 WHERE something = myQuery
   AND ( COUNT(SELECT whatever FROM MyTable
             WHERE something = myQuery) = 1)

但这太讨厌了,我想知道是否有一种更整洁的方法。

最佳答案

你能做:

SELECT whatever FROM
    (
       SELECT whatever, COUNT(*) As NumRecords
       FROM MyTable
       WHERE something = myQuery
       GROUP BY whatever
       HAVING NumRecords = 1
    )

关于sql - SQL Server仅返回单行或空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4214196/

10-12 06:07