Partition by filter

Vineet S 225 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
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,117 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
58 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,583 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114K 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 405 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 104.2K Reputation points MVP
    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