0

Table1

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

I want to have a query which produces the following result

4812 NULL
4610 NULL

So if any entry of the same NoteNr has a value in its TransactionID Column, the NoteNr should not be in the result of the query. The Resultset should only contain NoteNrs, if all entries of the NoteNr has no value in its TransactionID Column (NULL)

2
  • What queries have you attempted to achieve this? Commented Jul 11, 2018 at 7:51
  • @DKyleo tried an approach with MIN(CASE WHEN TransactionID IS NULL THEN 0 ELSE 1 END) = 0 but since in NoteNr 4711 is one entry NULL, this is not working Commented Jul 11, 2018 at 8:05

5 Answers 5

2

This should work:

SELECT DISTINCT *
FROM   Table1 t
WHERE  NOT EXISTS (   SELECT 1
                      FROM   Table1
                      WHERE  NoteNr = t.NoteNr
                             AND TransactionId IS NOT NULL );
Sign up to request clarification or add additional context in comments.

1 Comment

This needs a DISTINCT to return the same results in question.
0

This should do it

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

Comments

0

USE CAN USE CTE to achieve this

;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

Comments

0

This will help.

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

Comments

0

This is the most efficient way to avoid the grouping needed to remove duplicates:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.