我的数据如下:
Name Status Sub status End Date
AAA Active High N/A
AAA Inactive Intermediate 12/1/17
BBB Inactive High 12/31/17
BBB Inactive Intermediate 12/1/17
BBB Inactive Low 12/14/17
CCC Inactive Intermediate 9/11/17
CCC Inactive Low 9/21/17
DDD Inactive Intermediate 10/12/17
DDD Inactive Low 2/2/18
DDD Inactive Intermediate 9/21/17
DDD Inactive High 11/21/17
EEE Inactive Intermediate 8/2/17
EEE Inactive High 3/1/18
EEE Active Low N/A
输出:
Name Status Sub status End Date
BBB Inactive High 12/31/17
CCC Inactive Low 9/21/17
DDD Inactive Low 2/2/18
说明:
我需要看看
1-消除处于活动状态的那些 2-如果未激活,请选择结束日期为其所有结束日期的最大值的人员的不同名称和子状态
我尝试使用子查询来消除处于“活动”状态但未按预期工作的子查询。我应该用什么来达到我想要的输出!
PS:我使用postgres SQL
答案 0 :(得分:0)
select name, status, sub_status,end_date
where status='Inactive'
group by name
having end_date = max(end_date)
基本上,您要删除活动记录,然后按名称分组,只获取每组最大结束日期的记录。如果任何end_date为null或者您有任何具有相同名称和结束日期的记录,则可能需要对此进行扩展。
答案 1 :(得分:0)
with x as ( select Name, max(EndDate) MaxEndDate from tbl t1 where not exists (select 1 from tbl t2 where t2.Name = t1.Name and t2.Status = 'Active') group by Name ) select t1.Name, t1.Status, t1.SubStatus, t1.EndDate from tbl t1 join x on t1.Name = x.Name and t1.EndDate = x.MaxEndDate
name | status | substatus | enddate :--- | :------- | :-------- | :--------- BBB | Inactive | High | 2017-12-31 CCC | Inactive | Low | 2017-09-21 DDD | Inactive | Low | 2018-02-02
dbfiddle here