我有这个选择查询来选择21天前发生的特定事件:
select distinct
concat(firstname, ' ', lastname) as Who,
date_column
from
database s
left join
person p on s.key = p.key
where
type = 'granted' and
date_column < dateadd(day, -21, getdate()) and
p.deleted = 0;
该查询通过选择所有21天前被授予类型的人而起作用,但是我只需要21天前被授予访问权但不使用其卡(类型=已授予)的人的姓名
基本上,只有在“类型”列最后一次将其注册为授予的时间是21天之前,并且在21天内没有获得授予访问权限的情况下,才选择名称。
我希望这是有道理的。
谢谢
答案 0 :(得分:1)
您可以将其添加到where子句中:
and not exists(
select * from database s2
where s2.key=s.key
and s2.type = 'granted' and
s2.date_column > dateadd(day,-21,getdate())
)
或将查询更改为此,这将为您提供21天前提供的最新授权。结果略有不同,因为每个用户只能获得一行,但可能会为您提供所需的内容。
select
concat(firstname,' ',lastname) as Who,
max(date_column) as date_Column
from database s
left join person p on s.key = p.key
where type = 'granted' and p.deleted = 0
group by firstname, lastname
having max(date_column) < dateadd(day,-21,getdate())
答案 1 :(得分:0)
我对名为database
的表有些困惑,但是如果我理解正确的话:
如果是,则应为查询:
select
concat(firstname,' ',lastname) as Who,
date_column
from
person p
inner join database g on g.key = p.key
where
-- Basic conditions which you already had
g.type = 'granted' and
g.date_column < dateadd(day,-21,getdate()) and
p.deleted = 0 and
-- Not exists a record for the same person, with a different
-- type and a date after the grant date
not exists (
select *
from database s
where
s.key = p.key and
s.type <> 'granted' and
s.date_column >= g.date_column
);
答案 2 :(得分:0)
如何?
select distinct
concat(firstname, ' ', lastname) as Who,
date_column
from
database s
left join
person p on s.key = p.key
where
type = 'granted' and
date_coumn between dateadd(date_column,-21,cast(getDate() as date)) AND cast(getDate() as date)
and p.deleted = 0;