根据表数据而非当前日期获取可显示30天的查询

时间:2016-09-24 01:21:25

标签: sql oracle

我想从3个表及其行中提取数据,如下所示:
**RentalAgreement – CustID,AgreementID(PK) and AgreementDate **Movie Rented – AgreementID(PK), RentalAmount and PercentReductionApplied,MovieID(FK) **Movie – MovieID(PK), Name, Released

我需要根据表格而不是当前数据显示过去30天的数据。 我怎样才能实现这一目标? 我的尝试:

SELECT TRIM(CustID),AgreementDate , RentalAmount    
             ,PercentReductionApplied , MovieID , Name , Released
FROM RentalAgreement, MovieRented, Movie
WHERE RentalAgreement.AgreementID = MovieRented.AgreementID
AND Movie.MovieID = MovieRented.MovieID
AND AgreementDate BETWEEN MAX(AgreementDate) AND MAX(AgreementDate)-30;

2 个答案:

答案 0 :(得分:0)

问题在于MAX(协议日期)。这是一个聚合函数 - 在处理WHERE子句之后,您只能在查询的最后一个阶段(在SELECT子句中)访问它。这意味着您需要一个不同的查询来首先计算MAX - 并将其用作整体(外部)查询中的子查询。

最好使用现代的SQL标准连接语法。将这两者放在一起:

SELECT TRIM(CustID),AgreementDate , RentalAmount    
             ,PercentReductionApplied , MovieID , Name , Released
FROM RentalAgreement
     join MovieRented on RentalAgreement.AgreementID = MovieRented.AgreementID
     join Movie       on Movie.MovieID               = MovieRented.MovieID
     cross join (select max(agreementdate) as max_date from rentalagreement) m
where AgreementDate BETWEEN m.max_date AND m.max_date - 30;

为什么需要TRIM(custID)?这很不寻常。同样奇怪的是,ProtocolID是MovieRented中的PRIMARY键。但这些并不是您的查询无效的原因。

答案 1 :(得分:0)

DECLARE @StartDate DATETIME,@ EndDate DATETIME

SELECT @StartDate = MAX(AgreementDate)FROM RentalAgreement SET @EndDate = DATEADD(DAY,-30,@ StartDate)

SELECT TRIM(CustID),AgreementDate,RentalAmount
             ,PercentReductionApplied,MovieID,Name,已发布 来自RentalAgreement,MovieRented,电影 WHERE RentalAgreement.AgreementID = MovieRented.AgreementID AND Movie.MovieID = MovieRented.MovieID 与@StartDate和@EndDate之间的协议日期