2013-12-08 97 views
0

我有以下代碼:別名子查詢不工作

SELECT 
CU.customer_ID AS "Customer ID", 
CU.cust_LNAME AS "Last Name", 
CU.cust_FNAME AS "First Name", 
RH.movie_ID AS "Movie ID", 
MO.movie_title AS "Movie Title", 
MO.release_year AS "Release Year", 
(
SELECT COUNT(*) FROM RentalHistory RH2 WHERE RH2.movie_ID = RH.movie_ID AND RH2.customer_ID = RH.customer_ID HAVING COUNT(*) > 1 
) "Nbr. Of Times Rented" 
FROM Customer CU 
RIGHT JOIN Rentalhistory RH ON (RH.customer_ID = CU.customer_ID) 
INNER JOIN Movie MO ON (MO.movie_ID = RH.movie_ID) 
GROUP BY CU.customer_ID, RH.movie_ID  
HAVING "Nbr. Of Times Rented" > 1 
ORDER BY CU.cust_LNAME ASC, CU.cust_FNAME ASC; 

我不斷收到無效的標識符別名子查詢?任何想法,我做錯了什麼?

回答

0

我不認爲你需要子查詢。這是否做你想要的?

SELECT CU.customer_ID AS "Customer ID", 
     CU.cust_LNAME AS "Last Name", 
     CU.cust_FNAME AS "First Name", 
     RH.movie_ID AS "Movie ID", 
     MO.movie_title AS "Movie Title", 
     MO.release_year AS "Release Year", 
     COUNT(*) as "Nbr. Of Times Rented" 
FROM Customer CU RIGHT JOIN 
    Rentalhistory RH 
    ON RH.customer_ID = CU.customer_ID INNER JOIN 
    Movie MO 
    ON MO.movie_ID = RH.movie_ID 
GROUP BY CU.customer_ID, RH.movie_ID  
HAVING count(*) > 1 
ORDER BY CU.cust_LNAME ASC, CU.cust_FNAME ASC; 
+0

實際上確實在某種程度上工作,客戶字段顯示爲空,可能必須調整JOIN來解決該問題。 – user3015045

+0

@ user3015045。 。 。如果您在租賃歷史記錄表中存在不在客戶表中的'customer_id'(或者它們恰好在客戶表中爲「NULL」),就會發生這種情況。在大多數數據庫中,您不需要'Customer'和'RentalHistory'之間的'right join'。 –