使用其他列的最小日期检查列的值

时间:2017-11-24 10:18:48

标签: sql sql-server join

我有一张桌子

  id     | guid | Status 
  ------ | -----| ----------
  1      | 123  | 2
  2      | 456  | 2 
  3      | 789  | 2

另一张表

 id.    | modified date           | Status 
 ------ | ----------------------- | ----------
 1      | 26-08-2017 04:05        | 0
 1      | 26-08-2017 10:50        | 0
 1      | 01-09-2017 02:03        | 0
 1      | 02-09-2017 13:43        | 2
 2      | 26-08-2017  03:04       | 0
 2      | 26-08-2017  11:04       | 2
 2      | 02-09-2017  18:03       | 2
 3      | 01-09-2017  03:45       | 0
 3      | 01-09-2017  12:04       | 0
 3      | 03-09-2017  17:08       | 2

在第一个表中,只要状态值发生变化,它就会记录在另一个表中。

我想要那些在第一次保存状态时状态值保持为0的ID(即该事务的最小日期)。

Id 1在26日第一次被保存,然后整天它的值保持为0(我必须仅检查第一个日期)。对于26中的id 2,它保存为0然后同一天更改为2.因此它将在这种情况下不会出现。对于id 3,它在第一次约会时仍为0。

所需的o / p将是 ID 1 3

2 个答案:

答案 0 :(得分:1)

您可以使用下面的查询

select t1.id 
from table2 t1 
inner join
(
select id, 
min(modifieddate) over (partition by id) startDateTime,
max(Status) over (partition by id,cast(modifieddate as date)) maxStatusOnStartDay
from table2
)t2
on t1.id=t2.id and 
cast(t1.modifieddate as date)=cast(t2.startDateTime as date)
and t2.maxStatusOnStartDay=0
group by t1.id

see live demo

答案 1 :(得分:0)

尝试此查询:

select id from (
    select id,
       CAST(modified_date as date) as [modified_date],
       [status],
       MIN(CAST(modified_date as date)) over (partition by id) as [first_saved]
    from TABLE_NAME
) as A where modified_date = first_saved
group by id
having SUM([status]) = 0