具有计数错误的多表查询

时间:2014-03-05 20:22:27

标签: sql oracle

每当我向下面的select语句添加一个计数时,它会导致它给我一个错误,我不确定原因:

select "WorkOrder"."WorkOrderID", "Vehicles"."Model", "Vehicles"."Color",
"Vehicles"."LicensePlate", COUNT("WorkOrderPart"."WorkPartID") AS "Parts"
FROM "WorkOrder", "Vehicles", "WorkOrderPart"
WHERE "WorkOrder"."VIN" = "Vehicles"."VIN" AND
"WorkOrder"."WorkOrderID" = "WorkOrderPart"."WorkOrderID";

每当我运行它时,我都会收到以下错误:

select "WorkOrder"."WorkOrderID", "Vehicles"."Model", "Vehicles"."Color",
       *
ERROR at line 1:
ORA-00937: not a single-group group function

我该怎么办?我正在使用Oracle数据库运行SQL命令行。

1 个答案:

答案 0 :(得分:6)

当您拥有count(或其他汇总功能)时,您需要group by非聚合项目

select 
     "WorkOrder"."WorkOrderID", 
     "Vehicles"."Model", 
     "Vehicles"."Color",
     "Vehicles"."LicensePlate", 
     COUNT("WorkOrderPart"."WorkPartID") AS "Parts"
FROM "WorkOrder", "Vehicles", "WorkOrderPart"
WHERE "WorkOrder"."VIN" = "Vehicles"."VIN" 
AND "WorkOrder"."WorkOrderID" = "WorkOrderPart"."WorkOrderID"
group by  "WorkOrder"."WorkOrderID", "Vehicles"."Model", "Vehicles"."Color",
"Vehicles"."LicensePlate"

顺便说一句,使用显式连接(除非您使用的是oracle的史前版本)而不是where子句

被认为是一种好习惯。
FROM "WorkOrder" 
     inner join "Vehicles" on "WorkOrder"."VIN" = "Vehicles"."VIN" 
     left join "WorkOrderPart" on "WorkOrder"."WorkOrderID" = "WorkOrderPart"."WorkOrderID"