SQL 查询 - 查询时过滤新记录

SQL Query -filtering for new record while querying

我有以下 table,比如包含这些记录的订阅

app_id  Status  Date
1   Submitted   d1
1   Open        d2
1   Approved    d3
2   Submitted   d4
2   Submitted   d5(d4<d5)
3   Open        d6
3   Approved    d7
4   Open        d8
4   Declined    d9

我的输出逻辑是:

1) 对于每个 app_id,我们需要选择提交状态的日期。

2) 如果 app_id 有 2 条状态为已提交的记录,我们需要选择最早提交日期的记录。

3) 如果没有提交日期,则取 "Approved" 或 "Declined" 状态的日期。

我上面 table 的输出应该是这样的

 app_id   date
   1       d1
   2       d4
   3       d7
   4       d9

你能告诉我如何编写 sql 相同的查询吗?

基于已删除的示例数据(为什么...)?

CREATE TABLE #Record (App_id int,
                      [Status] varchar(12),
                      [date] char(2));

INSERT INTO #Record
VALUES (1,'Submitted','d1'),
       (1,'Open     ','d2'),
       (1,'Approved ','d3'),
       (2,'Submitted','d4'),
       (2,'Submitted','d5'),
       (3,'Open     ','d6'),
       (3,'Approved ','d7'),
       (4,'Open     ','d8'),
       (4,'Declined ','d9');
GO

WITH CTE AS(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY App_Id
                              ORDER BY CASE [Status] WHEN 'Submitted' THEN 0 ELSE 1 END ASC, [date] ASC) AS RN
    FROM #Record)
SELECT App_id,
       [Status],
       [date]
FROM CTE
WHERE RN = 1;

GO
DROP TABLE #Record;

试试这个

select app_id, min(thedate) 
from #tryout
where (
        thestatus='Submitted'  OR (thestatus = 'Approved' or thestatus='Declined')
      )
group by app_id