简体   繁体   中英

Limiting query results by date

I have a working query constructed by multiple Join clauses. One of the columns is RecordDate. I want to display only records under the following condition: RecordDate > ((Max(RecordDate) for the whole report)-40) days. In other words, records dating Max date or 40 days earlier. I noticed that I cannot calculate the date-40 in the WHERE clause and so I have created a date_CTE query to give me the calculated "old-date".

WITH date_CTE(PrevDate,sd) AS
    (SELECT dateadd(DAY,-33,max(ScanDate)),ScanDate
    FROM v_TthreatsCombined
    GROUP BY scanDate)
    SELECT MAX(prevDate) FROM date_CTE

I have failed to join the result of "SELECT MAX(prevDate) FROM date_CTE" into WHERE.

Query looks a little like this:

SELECT col1,col2.col3,ScanDate
FROM table1
Left Join ....
Left Join ...
WHERE condition1 AND (condition2 OR condition3) AND <SELECT MAX(prevDate) FROM date_CTE>

Am I at all on the right path? Thank you for helping.

Amos

One option uses window functions. Based on your pseudo-code, this would look like:

select *
from (
    select col1, col2, col3, scandate, max(scanDate) over() maxScanDate
    from table1
    left join ....
    left join ...
    where condition1 and (condition2 or condition3)
) t
where scanDate > dateadd(day, -33,  maxScanDate)

I would just use the CTE (or just a sub-query) to calculate the start date. One way or the other, you need to JOIN the CTE or sub-query into your FROM clause. I'd do the filtering on the join.

DECLARE @t TABLE (dt DATE, val INT);

INSERT @t (dt, val)
VALUES ('20200101', 1),
       ('20200201', 2),
       ('20200301', 3)


WITH date_CTE(StartDt) AS 
(
    SELECT DATEADD(DAY, -40, MAX(dt)) AS StartDt
    FROM @t
)
SELECT val
FROM @t AS T
JOIN
    date_CTE AS d
    ON T.dt >= d.StartDt

Max date minus forty days returns the two latest entries in the table:

+-----+
| val |
+-----+
|   2 |
|   3 |
+-----+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM