Oracle SQL计数字段由另一个字段分组

时间:2014-04-16 14:08:02

标签: sql oracle count group-by oracle-sqldeveloper

我在下面有一个小查询,我希望每个HOUSE_ID的计数和LOCATION_ID分组,但不是LOCATION_ID分组,因为HOUSE_ID& #39; s是不同的。无论HOUSE_ID是什么,我都希望LOCATION_IDHOUSE_ID进行计数。

QUERY

SELECT 
COUNT(HOUSE_ID) AS Count,
LOCATION_ID,
ZONE,
AREA
FROM TABLE
WHERE SITE_ID = 'ABC'
AND LOCATION_ID NOT LIKE ('%LAND%')
GROUP BY LOCATION_ID, HOUSE_ID, ZONE, AREA

预期结果

_____________________________
|Count|LOCATION_ID|ZONE|AREA|
|¯¯¯¯¯|¯¯¯¯¯¯¯¯¯¯¯|¯¯¯¯|¯¯¯¯|
|  4  |  LOCA     | 2  |  1 |
|  7  |  LOCB     | 6  |  2 |
|  3  |  LOCC     | 3  |  1 |
|  9  |  LOCD     | 5  |  7 |
|  6  |  LOCE     | 7  |  4 |
|  2  |  LOCF     | 2  |  1 |
|  8  |  LOCG     | 7  |  5 |
|  7  |  LOCH     | 9  |  1 |
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

实际结果

_____________________________
|Count|LOCATION_ID|ZONE|AREA|
|¯¯¯¯¯|¯¯¯¯¯¯¯¯¯¯¯|¯¯¯¯|¯¯¯¯|
|  1  |  LOCA     | 2  |  1 |
|  1  |  LOCA     | 6  |  2 |
|  1  |  LOCA     | 3  |  1 |
|  1  |  LOCA     | 5  |  7 |
|  1  |  LOCA     | 7  |  4 |
|  1  |  LOCA     | 2  |  1 |
|  1  |  LOCA     | 7  |  5 |
|  1  |  LOCA     | 9  |  1 |
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

2 个答案:

答案 0 :(得分:1)

您必须从group by子句中删除HOUSE_ID。 如果没有源数据,我只能猜测您还需要ZONEAREA列的聚合函数,例如MAX。尝试以下解决方案:

SELECT 
COUNT(HOUSE_ID) AS Count,
LOCATION_ID,
MAX(ZONE),
MAX(AREA)
FROM TABLE
WHERE SITE_ID = 'ABC'
AND LOCATION_ID NOT LIKE ('%LAND%')
GROUP BY LOCATION_ID

答案 1 :(得分:0)

得到它,需要数(*)!!

SELECT 
COUNT(*) AS Count,
SUM(AREA) AS AREA
LOCATION_ID,
ZONE,
FROM TABLE
WHERE SITE_ID = 'ABC'
AND LOCATION_ID NOT LIKE ('%LAND%')
GROUP BY LOCATION_ID, ZONE