I have 2 tables auction and customer
auction
custId|itemName|yearsUsed|bidPrice
1 | MacBook| 2 | 1500
3 | Dell | 1 | 1000
2 | MacBook| 2 | 1500
customer
custId|custName
1 | tom
2 | jerry
3 | susan
I want to query for those customers name, the item name and the bidding price for who have bided the same price for an item and the years used by the owner as well
The following query returns the item name which has the same bidding price by the customers
SELECT ac.itemName,
ac.yearsUsed,
ac.bidPrice
FROM auction ac
GROUP BY ac.itemName,
ac.yearsUsed,
ac.bidPrice
HAVING COUNT(*) > 1;
output
itemName yearsUsed bidPrice
----------------------------
MacBook 2 1500
Now I want to query for the customer name who had bid the same price for the item
SELECT ac.itemName,
ac.yearsUsed,
ac.bidPrice
FROM auction ac
INNER JOIN (
SELECT custName
FROM customer
) c
ON c.custId = ac.custId
GROUP BY ac.itemName,
ac.yearsUsed,
ac.bidPrice
HAVING COUNT(*) > 1;
I get an error
ERROR at line 1:
ORA_00904:"C"."CUSTID": invalid identifier
I am using sqlplus
You must add custid
in the inner query.
SELECT
ac.itemName,
ac.yearsUsed,
ac.bidPrice
FROM
auction ac INNER JOIN
(SELECT custName,
-- The following CUSTID was missing:
CUSTID
FROM customer) c ON c.custId = ac.custId
GROUP BY ac.itemName,ac.yearsUsed,ac.bidPrice
HAVING COUNT(*) > 1;
However , in your case, the subquery is not necessary.
SELECT
ac.itemName,
ac.yearsUsed,
ac.bidPrice
FROM
auction ac INNER JOIN
customer c ON c.custId = ac.custId
GROUP BY
ac.itemName,
ac.yearsUsed,
ac.bidPrice
HAVING COUNT(*) > 1;
If you also need, as per your comment, the customers' names, then you need to go with the analytical expression count(*) over(...)
:
select
custName,
itemName,
yearsUsed,
bidPrice
from (
SELECT
c.custName,
ac.itemName,
ac.yearsUsed,
ac.bidPrice,
count(*) over (partition by
ac.itemName,
ac.yearsUsed,
ac.bidPrice) cnt
FROM
auction ac INNER JOIN
customer c ON c.custId = ac.custId
)
where
cnt > 1
Try like this
SELECT
ac.itemName,
ac.yearsUsed,
ac.bidPrice,
c.custName
FROM auction ac
LEFT JOIN customer c ON c.custId = ac.custId
GROUP BY ac.itemName,ac.yearsUsed,ac.bidPrice
HAVING COUNT(*) > 1;
cust_id
is missing from the inner select
. By why use an inner select
?
select ac.itemname
, ac.yearsused
, ac.bidprice
from auction ac
inner
join customer c
on c.custid = ac.custid
group
by ac.itemname
, ac.yearsused
, ac.bidprice
having count(*) > 1
;
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.