SQL连接两个表并计数

时间:2016-06-02 16:11:39

标签: sql oracle

我想检索拥有超过1辆汽车的所有客户。

我有这段代码:

SELECT c.fname, 
       c.lname, 
       c.cid, 
       Count(v.cid) AS nmbrofvehicle 
FROM   customer c 
LEFT JOIN vehicle v 
       ON c.cid = v.cid 
GROUP  BY c.fname; 

但它会返回此错误:

  

ORA-00979:不是GROUP BY表达式

3 个答案:

答案 0 :(得分:2)

select c.fname, c.lname, c.cid, count(v.cid) as nmbrofvehicle
from customer c left join vehicle v on c.cid = v.cid 
group by c.fname, c.lname, c.cid
having count(*) > 1;

答案 1 :(得分:1)

您遇到的问题是您试图将未分组数据(例如姓氏)分组。

某些数据库(例如MySQL)非常宽容并尝试这样做 - 但Oracle不是。

试试这个:

SELECT a.cid
     , a.fname
     , a.sname
     , NVL(b.nmbrofvehicle, 0) AS nmbrofvehicle 
  FROM customers a
  LEFT JOIN ( SELECT z.cid
                   , COUNT(z.cid) AS nmbrofvehicle
                FROM vehicle z
               GROUP BY z.cid
            ) b
    ON ( a.cid = b.cid );

这将从customers获取数据,并从vehicles上的cid表中加入任何匹配数据,或者通过此NVL函数返回0。

答案 2 :(得分:0)

c.cid移除select并将c.lname添加到group by

SELECT c.fname, c.lname, 
       Count(v.cid) AS nmbrofvehicle 
FROM customer c JOIN
     vehicle v 
     ON c.cid = v.cid 
GROUP BY c.fname, c.lname
HAVING COUNT(*) > 1;

不需要LEFT JOIN,因为您需要至少一次匹配。