我试图排除在旅行表上没有条目的用户,但是如果用户不是过期用户(即修改日期不超过13个月),则将其包括在内
modifieddate字段位于用户表
上我无法找到允许以下方式返回的方法
但不返回
我在下面提供了我的代码。任何帮助赞赏
DECLARE @dt datetime, @months int
SET @dt = GETDATE()
SET @months = -13
select distinct app.*
from appuser app
inner join
(
select user_id from appuser where user_id not in (
--Get app users that have been on any approved trips in the last x months
select distinct app.user_id
from appuser app
join trip_user tu
on tu.user_id = app.user_id
join trip t
on t.trip_id = tu.trip_id
where
trip_date between DATEADD(MONTH, -13, GETDATE()) and Getdate()
-- approved or completed trip
and trip_status_id in (2,3)
)
) as PassNotOnTripInLast13Mons
on app.user_id = PassNotOnTripInLast13Mons.user_id
left join
(
select distinct app.user_id from appuser app
join trip_user tu
on tu.user_id = app.user_id
join trip t
on t.trip_id = tu.trip_id
where
trip_date > DATEADD(MONTH, -13, GETDATE())
) as PassOnTripOver13Mons
on app.user_id = PassOnTripOver13Mons.user_id
left join (
select distinct user_id
from appuser
where DATEDIFF(MONTH, ModifiedDate , GETDATE()) > 13
) as PassOnSystemOver13Mons
on app.user_id = PassOnSystemOver13Mons.user_id
where
--is a passanger
isPassenger = 1
--user does not have an unmet need
and app.user_id not in (select passenger_id from unmet_needs where passenger_id = app.user_id)
-- don't redo a passange alread obfusticated
and obfusticated = 0
and isNTA = 0
and isTCUDispatcher = 0
and isProviderUser = 0
and isDriver = 0
答案 0 :(得分:1)
以下是我对您的要求的最佳理解:您需要返回已经旅行过的用户,或者在过去的13个月内进行过修改的用户。您的代码中还有一个未记录的要求,仅包括未被诽谤的乘客,并且只计算已批准的旅行(trip_status_id in (2,3)
)。
基于这些要求,我认为以下简化代码可以完成您要完成的任务:
select app.*
from
appuser app
left join
tripuser tu on
app.user_id = tu.user_id
left join
trip on
tu.trip_id = trip.trip_id
and trip_status_id in (2,3) -- approved trip
and trip_date >= DATEADD(MONTH, -13, GETDATE())
WHERE
(
trip.trip_id is null and
app.ModifiedDate <= DATEADD(MONTH, -13, GETDATE())
)
--is a passenger
and isPassenger = 1
--user does not have an unmet need
and app.user_id not in (select passenger_id from unmet_needs where passenger_id = app.user_id)
-- don't redo a passange alread obfusticated
and obfusticated = 0
and isNTA = 0
and isTCUDispatcher = 0
and isProviderUser = 0
and isDriver = 0