MSSQL查询:如果列中的所有值都为空,则返回结果

时间:2018-07-11 07:49:45

标签: sql-server

表1

NoteNr | TransactionID
----------------------
4711   | NULL
4711   | 123
4812   | NULL
4913   | 444
4610   | NULL
4610   | NULL

我想要一个产生以下结果的查询

4812 NULL
4610 NULL

因此,如果同一NoteNr的任何条目在其TransactionID列中都有值,则NoteNr不应出现在查询结果中。如果NoteNr的所有条目在其TransactionID列(NULL)中没有值,则结果集应仅包含NoteNrs

5 个答案:

答案 0 :(得分:2)

这应该有效:

SELECT DISTINCT *
FROM   Table1 t
WHERE  NOT EXISTS (   SELECT 1
                      FROM   Table1
                      WHERE  NoteNr = t.NoteNr
                             AND TransactionId IS NOT NULL );

答案 1 :(得分:0)

这应该做

select NoteNr, NULL From (
       select NoteNr, sum(TransactionID) as c From [table] group by NoteNr
) as t1 where t1.c IS NULL

答案 2 :(得分:0)

使用可以使用CTE来实现

;WITH CTE
AS
(
SELECT *,ROW_NUMBER()OVER(PARTITION BY NoteNr  ORDER BY NoteNr)Rownum FROM #TEMP a   WHERE TransactionID IS NULL AND NoteNr NOT IN (SELECT NoteNr FROM #TEMP WHERE TransactionID IS NOT NULL)
)
SELECT NoteNr,TransactionID FROM CTE WHERE Rownum=1

答案 3 :(得分:0)

这会有所帮助。

SELECT NoteNr
    ,TransactionID
FROM (
    SELECT DISTINCT NoteNr
        ,TransactionID
        ,ROW_NUMBER() OVER (
            PARTITION BY NoteNr ORDER BY NoteNr
            ) AS rowno
    ) AS main
WHERE rowno = 1

答案 4 :(得分:0)

这是避免删除重复项所需的分组的最有效方法:

Select notenr, Null as TransactionId from @table1
except
select notenr, Null as TransactionId from @table1 where TransactionID is not null