Partition by filter

Vineet S 1,390 Reputation points
2024-06-14T14:34:28.8633333+00:00

Hey Team

I have table where A values comes then E value should be filter or else E value should be there partition by data and mpr column

User's image

expected values

User's image

SQL Server | SQL Server Transact-SQL
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 125.8K Reputation points
    2024-06-14T15:05:42.24+00:00

    Check if this query works, or give counterexamples:

    select mpr, Date1, [Read] from MyTable
    except
    select mpr, Date1, 'E' from MyTable where [Read] = 'A'
    order by Date1
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Naomi Nosonovsky 8,881 Reputation points
    2024-06-14T15:21:24.4+00:00

    Please try this query:

    ;with cte as (select *, row_number() over (partition by mpr, Date1 order by read) as Rn from Results)
    select * from cte where Rn = 1
    
    0 comments No comments

  2. Erland Sommarskog 129.4K Reputation points MVP Volunteer Moderator
    2024-06-14T21:01:30.2733333+00:00

    This answer is coming late. I composed it, but apparently forgot to click the Post button.

    CREATE TABLE #temp (mpr    varchar(30) NOT NULL,
                        Date1  date        NOT NULL,
                        read_  char(1)     NOT NULL)
    INSERT #temp (mpr, Date1, read_)
       VALUES('test', '20040101', 'A'),
             ('test', '20040101', 'E'),
             ('test', '20050101', 'A'),
             ('test', '20050101', 'E'),
             ('test', '20060101', 'A'),
             ('test', '20070101', 'E')
    go
    SELECT * FROM #temp
    DELETE #temp
    FROM   #temp a
    WHERE  read_ = 'E'
      AND  EXISTS (SELECT *
                   FROM   #temp b
                   WHERE  b.mpr = a.mpr
                     AND  b.Date1 = a.Date1
                     AND  b.read_ = 'A')
    go
    SELECT * FROM #temp
    go
    DROP TABLE #temp
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.