我想检索拥有超过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表达式
答案 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
,因为您需要至少一次匹配。