[英]SQL(inner join with select statement)
I have 2 tables auction and customer 我有2张桌子拍卖和客户
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 我正在使用sqlplus
You must add custid
in the inner query. 您必须在内部查询中添加
custid
。
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(...)
: 如果您还需要根据评论添加客户的姓名,则需要使用解析表达式
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
. 内部
select
缺少cust_id
。 By why use an inner select
? 为什么要使用内部
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
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.