SQL(带select语句的内连接)

时间:2014-02-14 08:23:56

标签: sql oracle sqlplus

我有2张桌子拍卖和客户

拍卖

custId|itemName|yearsUsed|bidPrice
   1  | MacBook|    2    |  1500
   3  |  Dell  |    1    |  1000
   2  | MacBook|    2    |  1500

客户

 custId|custName
   1   | tom
   2   | jerry
   3   | susan

我想查询这些客户的名称,项目名称和出价,以确定某个项目的价格和所有者使用的年份相同的费用

以下查询返回客户具有相同出价的商品名称

  SELECT ac.itemName,
         ac.yearsUsed,
         ac.bidPrice 
    FROM auction ac 
GROUP BY ac.itemName,
         ac.yearsUsed,
         ac.bidPrice 
  HAVING COUNT(*) > 1;

输出

itemName yearsUsed  bidPrice
----------------------------
 MacBook     2       1500

现在,我想查询为该项目出价相同的客户名称

  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;

我收到错误

ERROR at line 1:
ORA_00904:"C"."CUSTID": invalid identifier

我正在使用sqlplus

3 个答案:

答案 0 :(得分:4)

您必须在内部查询中添加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;

但是,在您的情况下,子查询不是必需的。

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;

如果根据您的评论还需要客户的姓名,那么您需要使用分析表达式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

see also this SQL fiddle

答案 1 :(得分:0)

试试这个

     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;

答案 2 :(得分:0)

内部cust_id缺少

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
;