使用count函数但在select语句中有多个字段以查看更多数据

时间:2018-02-16 21:56:08

标签: sql oracle

select 
    eq_locations.equipment,eq_locations.description, 
    eq_locations.marked_as_deleted count(wo_work_order.equipment)
 FROM  
    eq_locations, wo_work_order 
where 
    eq_locations.equipment=wo_work_order.equipment and 
    eq_locations.plant='908' and eq_locations.marked_as_deleted = '0'
group by 
    eq_locations.equipment
order by 
    eq_locations.equipment

我得到的错误是

  

'第2行的错误ORA-00923:找不到FROM关键字'。

当我运行以下查询时,我得到了设备及其在第二个表中使用的次数(wo_work_order),但是我需要第一个表中的描述和marked_as_deleted字段(eq_locations)... < / p>

select eq_locations.equipment, count(wo_work_order.equipment) from eq_locations
left outer join wo_work_order
on eq_locations.equipment = wo_work_order.equipment
where eq_locations.plant='908'
group by eq_locations.equipment
order by eq_locations.equipment

2 个答案:

答案 0 :(得分:1)

除了在,之前添加缺少的逗号count(wo_work_order.equipment)之外,您还需要在group by子句中添加eq_locations.descriptioneq_locations.marked_as_deleted

select 
    eq_locations.equipment,eq_locations.description, 
    eq_locations.marked_as_deleted, count(wo_work_order.equipment)
 FROM  
    eq_locations, wo_work_order 
where 
    eq_locations.equipment=wo_work_order.equipment and 
    eq_locations.plant='908' and eq_locations.marked_as_deleted = '0'
group by 
    eq_locations.equipment, eq_locations.description, eq_locations.marked_as_deleted
order by 
    eq_locations.equipment

答案 1 :(得分:0)

使用JOIN ON语法进行连接。不要使用a,b语法。此外,更喜欢简单的表别名,而不是使用整个表名称。我认为您需要使用LEFT JOIN的第二个查询来获取wo_work_order表中缺少设备的0计数。此查询应该可以正常工作。

 SELECT  e.equipment,
         e.description,
         e.marked_as_deleted,
         COUNT(w.equipment)
FROM     eq_locations e LEFT OUTER JOIN wo_work_order w
ON e.equipment=w.equipment
AND      e.plant='908'
AND      e.marked_as_deleted = '0'
GROUP BY e.equipment,
         e.description,
         e.marked_as_deleted
ORDER BY e.equipment;