2

I'm working on simple queries but can't figure out how to modify to produce the below output.

  Number Name Flag
  1      ABC   NULL
  1      DEF   FG
  1      DEF   NULL

I need to produce this output:

  Number Name Flag
  1      ABC   NULL
  1      DEF   FG

The logic is when Number and Name are same, take the rows with the Flag.

1
  • 3
    What happens if you have another row containing 1 DEF GH? Commented Feb 20, 2012 at 21:49

2 Answers 2

2

Simplest way, but I don't know if that meets your requirements if there is more than one non-NULL value.

SELECT Number, Name, Flag = MAX(Flag)
  FROM dbo.Table
  GROUP BY Number, Name;
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe something like this:

First some test data:

DECLARE @tbl TABLE(Number INT,Name VARCHAR(10),Flag VARCHAR(3))

INSERT INTO @tbl
VALUES
    (1,'ABC',NULL),
    (1,'DEF','FG'),
    (1,'DEF',NULL)

The the query like this:

;WITH CTE AS
(
    SELECT
        RANK() OVER(PARTITION BY Name ORDER BY Flag DESC) AS iRank,
        tbl.Number,
        tbl.Name,
        tbl.Flag
    FROM
        @tbl AS tbl
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.iRank=1

1 Comment

Perfect !!! That worked the best for the scenario , I was looking for .. Thanks !!!!

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.