2016-09-24 63 views
0

枝我想如下從中提取3個表及其行的數據顯示30天的查詢:
**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; 

回答

0

問題是與MAX(agreementdate)。這是一個聚合函數 - 在處理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)?這很不尋常。奇怪的是,AgreementID是MovieRented中的PRIMARY鍵。但這些不是你的查詢不起作用的原因。

0

DECLARE @StartDate DATETIME,@結束日期DATETIME

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

SELECT TRIM(客戶ID) ,AgreementDate,RentalAmount
,PercentReductionApplied,MovieID,名稱,發行日期 FROM RentalAgreement,MovieRented,電影 WHERE RentalAgreement.AgreementID = MovieRented.AgreementID AND Movie.MovieID = MovieRented.MovieID AND AgreementDate乙ETWEEN @StartDate AND @EndDate

相關問題