SQL Group By Function

时间:2014-01-12 23:52:58

标签: sql oracle

我需要过滤包含多个位置的状态的数据。我的代码是:

SELECT
  cc.country_id,
  cc.country_name,
  l.city,
  l.street_address,
  l.postal_code,
  l.state_province,
  count(*)
  FROM locations l, countries cc
 WHERE l.country_id = cc.country_id
 ORDER BY cc.country_id
 GROUP BY (cc.country_id, cc.country_name)
HAVING count(*) > 1;

我收到以下消息:

ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function"
*Cause:    
*Action:
Error at Line: 6 Column: 9

有什么问题?

3 个答案:

答案 0 :(得分:2)

所有不在聚合函数中的字段(count,sum,avg等)必须在group by子句中

那么,你应该有

group by cc.country_id, cc.country_name, 
         l.city, l.street_address, l.postal_code, l.state_province

或者你应该从select子句中删除这些字段,或者将它们放在select子句中的聚合函数中,或者更改你的查询。

顺便说一下,最好使用连接语法

替换

FROM locations l, countries cc
 where l.country_id = cc.country_id

通过

FROM location l
inner join countries cc on l.country_id = cc.country_id

最后,ORDER BY必须是查询中的最后一个语句

答案 1 :(得分:1)

查询存在以下几个问题:

  1. group by需要所有字段
  2. order by位置错误
  3. 它使用隐式而非显式join语法
  4. 以下内容应该有效:

     SELECT cc.country_id, cc.country_name, l.city, l.street_address,
            l.postal_code, l.state_province, count (*)
     FROM locations l join
          countries cc
          on l.country_id = cc.country_id
     group by cc.country_id, cc.country_name, l.city, l.street_address,
              l.postal_code, l.state_province
     having count(*) > 1
     order by cc.country_id;
    

    但是,如果您想计算国家/地区中的行数,请删除其他字段:

     SELECT cc.country_id, cc.country_name, count (*)
     FROM locations l join
          countries cc
          on l.country_id = cc.country_id
     group by cc.country_id, cc.country_name
     having count(*) > 1
     order by cc.country_id;
    

答案 2 :(得分:0)

您可以利用窗口函数

SELECT c.country_id, c.country_name, l.city, l.street_address, l.postal_code, l.state_province, l.l_count 
  FROM countries c JOIN 
(
  SELECT country_id, city, street_address, postal_code, state_province,
         COUNT(*) OVER (PARTITION BY country_id) l_count
    FROM locations
) l
    ON l.country_id = c.country_id
 WHERE l.l_count > 1
 ORDER BY c.country_id

这是 SQLFiddle 演示