简体   繁体   中英

Error while using INNER JOIN in PostgreSQL?

As I am new to PostgreSQL so I'm using PostgreSQL sample database for learning and practicing PostgreSQL. My problem statement is to find payment done for top 15 highest spending customers who rented movies during the days of April 10-13? My query is as follows:

SELECT customer.first_name,payment.amount
FROM customer
  INNER JOIN payment ON customer.customer_id = payment.customer_id
WHERE customer_id IN (SELECT customer_id 
                      FROM (
                        SELECT customer_id, SUM(amount)
                        FROM payment
                        WHERE extract(month from payment_date) = 4
                        AND extract(day from payment_date) BETWEEN 10 AND 13
                        GROUP BY customer_id
                        HAVING SUM(amount) > 5
                        ORDER BY SUM(amount) DESC
                        LIMIT 15
                      ) AS top_fifteen);

I'm getting following error:

relation "customer" does not exist

I'm not sure why am i getting this exception here, Can someone help me here in mitigating this issue? Any lead is highly appreciated.

use table alias name as like below and try

SELECT c.first_name,p.amount
FROM customer c
INNER JOIN payment p
ON c.customer_id = p.customer_id
WHERE c.customer_id IN 
(
SELECT customer_id FROM 
    (
SELECT  customer_id, SUM(amount)
FROM payment
WHERE extract(month from payment_date) = 4
AND extract(day from payment_date) BETWEEN 10 AND 13
GROUP BY customer_id
HAVING SUM(amount) > 5
ORDER BY SUM(amount) DESC
LIMIT 15) AS top_fifteen);

i rewrite your query as like below

select * from
 (
 select  c.first_name,c.last_name,
 sum(amount) as pay_amount,
 count(p.customer_id) pay_num from payment p
 inner join Customer c on  p.customer_id=c.customer_id
     where extract(month from p.payment_date) = 4
AND extract(day from p.payment_date) BETWEEN 10 AND 13
 group by c.first_name,c.last_name,p.customer_id
 ) T 
 order by pay_amount desc
 Limit 15

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