多表连接查询,在Oracle SQL中有计数

时间:2013-04-28 14:03:51

标签: sql oracle join

我正在尝试通过计算表格中属性编号出现的次数来计算YR_Inspection表中每个属性的检查次数,然后我需要在该属性所在的城市旁边显示该属性。和属性所属的分支在同一个查询中。这是我的ERD的链接,试图给出这个问题的一些背景,

enter image description here

http://www.gliffy.com/pubdoc/4239520/L.png

这是到目前为止的代码,它到目前为止工作但是只要我添加YR_Branch.CITY就得到了,

ORA-00979:不是GROUP BY表达式

SELECT YR_Property.PROPERTYNUM, COUNT(YR_Inspection.PROPERTYNUM) AS Number_of_inspections
FROM YR_Property  
INNER JOIN YR_Inspection 
    ON YR_Property.PROPERTYNUM = YR_Inspection.PROPERTYNUM 
JOIN YR_Branch
    ON YR_Property.BRANCHNUM = YR_Branch.BRANCHNUM
GROUP BY YR_Property.PROPERTYNUM

1 个答案:

答案 0 :(得分:2)

要为分支添加分支编号和城市,请为查询添加max值,如下所示:

SELECT YR_Property.PROPERTYNUM, 
       COUNT(YR_Inspection.PROPERTYNUM) AS Number_of_inspections,
       MAX(YR_Branch.BRANCHNUM) AS Branch_Number,
       MAX(YR_Branch.CITY) AS Branch_City
FROM YR_Property  
INNER JOIN YR_Inspection 
    ON YR_Property.PROPERTYNUM = YR_Inspection.PROPERTYNUM 
JOIN YR_Branch
    ON YR_Property.BRANCHNUM = YR_Branch.BRANCHNUM
GROUP BY YR_Property.PROPERTYNUM