按特定顺序在另一列中选择具有不同值的ID

时间:2019-02-27 22:04:37

标签: sql sql-server

情况:

我必须在另一个称为flag的列中提取具有不同值的ID。该值为0或1s。这些标志具有与之关联的特定日期。

目标:

我的目标有两个要求:

  1. 提取标志列中具有0和1的ID
  2. 并且只有那些在0之前带有标志1的标记(使用日期列)

当前查询:

我当前的查询仅提取0和1的那些。不确定如何获取0之前的1的

select id 
from table1 
where id IN ( select id from table1 group by id having count(distinct flag) >1)

小提琴数据:

CREATE TABLE table1
    ([id] varchar(13), [flag] int, [dates] DATE)


INSERT INTO table1
VALUES
    ('123', 1, '2019-01-01'),
    ('123', 1, '2019-01-02'),
    ('325', 0, '2019-01-01'),
    ('325', 1, '2019-01-02'),
    ('666', 1, '2019-01-02'),
    ('666', 0, '2019-01-01'),
    ('666', 1, '2019-01-02'),
    ('777', 1, '2019-01-01'),
    ('777', 0, '2019-01-02')

输出:

同时满足这两个条件的唯一ID是777

2 个答案:

答案 0 :(得分:1)

具有EXISTS:

select id from table1 t 
where flag = 1
and exists (
  select 1 from table1 where id = t.id and flag = 0 and dates > t.dates
)

请参见demo

要获取完整的行:

select * from table1 where id in (
  select id from table1 t 
  where flag = 1
  and exists (
    select 1 from table1 where id = t.id and flag = 0 and dates > t.dates
  )
)

请参见demo
或使用UNION:

select * from table1 t 
where flag = 1
and exists (
  select 1 from table1 where id = t.id and flag = 0 and dates > t.dates
)
union all
select * from table1 t 
where flag = 0
and exists (
  select 1 from table1 where id = t.id and flag = 1 and dates < t.dates
)
order by id, dates

请参见demo
还有一个:

select * from table1 t 
where exists (
  select 1 from table1 
  where id = t.id 
  and 1 - flag = abs(t.flag) 
  and (t.flag = 1 and dates > t.dates) or (t.flag = 0 and dates < t.dates)
)

请参见demo

答案 1 :(得分:1)

我将使用聚合和having

select id
from table1
group by id
having min(case when flag = 1 then date end) < max(case when flag = 0 then date end);

Here是db <>小提琴。

请注意,无论id的行数如何,此方法都有效。

如果要原始行,可以使用一个简单的方法in

select t1.*
from table1 t1
where t1.id in (select id
                from table1
                group by id
                having min(case when flag = 1 then date end) < max(case when flag = 0 then date end)
               );