How to select a group or record?

NguyenM2 25 Reputation points
2023-02-24T14:12:43.2833333+00:00

I have table: User's image

How can I select group of record contain status=open? (Group record with status = sent, received, open, close) and delete the rest.

Thank you. MN

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,364 questions
Access Development
Access Development
Access: A family of Microsoft relational database management systems designed for ease of use.Development: The process of researching, productizing, and refining new or existing technologies.
859 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 107.2K Reputation points
    2023-02-24T15:43:29.33+00:00

    Here is a query. Note that the first part is only to set up the test data. Normally, we prefer that you do this yourself to save our time. We cannot copy from an image, but if you give us a script, we can easily work with that.

    DECLARE @T TABLE (ID   int NOT NULL PRIMARY KEY,
                      Status varchar(10) NOT NULL)
    INSERT @T (ID, Status)
      VALUES(1, 'Sent'), (2, 'Whatever'), (3, 'Extra'), (4, 'Close'),
            (5, 'Junk'), (6, 'Close'), (7, 'Seven'),
            (8, 'Sent'), (9, 'Nove'), (10, 'Kymmenen'), (11, 'Close'),
            (12, 'Douze')
    
    SELECT a.*
    FROM   @T a
    OUTER  APPLY (SELECT TOP(1) b.Status
                  FROM   @T b
                  WHERE  b.ID < a.ID
                    AND  b.Status IN ('Sent', 'Close')
                  ORDER  BY b.ID DESC) AS b
    WHERE  'Sent' IN (a.Status, b.Status)
          
    
    1 person found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. 2023-02-24T17:58:27.41+00:00

    First using filter then select

    0 comments No comments