我在下面的查询中,交叉连接来自Persons表的Person_ID和来自DateRange的Date Range。这给了我范围内每个日期的Person_ID。
WITH DateRange(DateData) AS
(
SELECT CONVERT(DATETIME, '02/01/2016') as Date
UNION ALL
SELECT DATEADD(d,1,DateData)
FROM DateRange
WHERE DateData < CONVERT(DATETIME, '04/26/2016')
)
SELECT TBL_PERSONS.ID AS PERSON_ID, DateRange.DateData AS [DATE]
FROM
TBL_PERSONS
CROSS JOIN DateRange
WHERE TBL_PERSONS.STATUS='Active'
现在我要做的是每个Person_ID我想从同一个Person_ID的不同表中过滤最大日期的行。像这样的东西,
WITH DateRange(DateData) AS
(
SELECT CONVERT(DATETIME, '02/01/2016') as Date
UNION ALL
SELECT DATEADD(d,1,DateData)
FROM DateRange
WHERE DateData < CONVERT(DATETIME, '02/15/2016')
)
SELECT T1.PERSON_ID, T1.[DATE]
FROM
(SELECT TBL_PERSONS.ID AS PERSON_ID, DateRange.DateData AS [DATE]
FROM
TBL_PERSONS
CROSS JOIN DateRange
WHERE TBL_PERSONS.STATUS='Active'
) T1
GROUP BY T1.PERSON_ID, T1.[DATE]
HAVING T1.[DATE] <= (SELECT DATEADD(day, 5, MAX(CAST(event_time_Local AS DATE))) AS [DATE]
FROM TBL_EVENTS_HISTORY
WHERE PRIMARYID = T1.PERSON_ID
GROUP BY PRIMARYID )
但是这仍然给出了所有person_id的所有日期。我尝试使用Where而不是HAVING但没有任何变化。我也试过,下面但是同样的结果。
WITH DateRange(DateData) AS
(
SELECT CONVERT(DATETIME, '02/01/2016') as Date
UNION ALL
SELECT DATEADD(d,1,DateData)
FROM DateRange
WHERE DateData < CONVERT(DATETIME, '02/15/2016')
)
SELECT T1.PERSON_ID, T1.[DATE]
FROM
(SELECT TBL_PERSONS.ID AS PERSON_ID, DateRange.DateData AS [DATE]
FROM
TBL_PERSONS
CROSS JOIN DateRange
WHERE TBL_PERSONS.STATUS='Active'
) T1
JOIN
(SELECT PRIMARYID AS PERSON_ID, DATEADD(day, 5, MAX(CAST(event_time_Local AS DATE))) AS [DATE]
FROM TBL_EVENTS_HISTORY
GROUP BY PRIMARYID ) T2
ON T1.PERSON_ID = T2.PERSON_ID
AND T1.[DATE] <= T2.[DATE]
我的问题是,我做错了吗?或者甚至可以为每个组分别使用过滤器?
注意:我正在尝试构建独立于SQL Server或Oracle的查询。