如何在下面的查询中使用'GROUP BY'功能

时间:2017-03-08 09:53:30

标签: sql oracle group-by

在下面的代码中,我想只在group by条件中给出的三列上应用组函数。但它给出了错误,错误的参数数量。

/var/www/html-aliases/site -> /var/www/html/beta.site.com

3 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

SELECT * FROM (
    SELECT
        a.id,
        a.name,
        c.code,
        a.active_dt,
        a.inactive_dt,
        b.category,
        COUNT(1) OVER(PARTITION BY a.id, a.name, c.code) AS CNT
    FROM
        student a,
        class b,
        descrip c
    WHERE
        a.id=b.id AND
        a.id=c.id
)
WHERE CNT > 1

答案 1 :(得分:0)

如果我理解得很好,你只需要这个:

select a.id,a.name,  
       c.code,
       a.active_dt,
       a.inactive_dt,
       b.category,
       count(*) count
from student a,class b, descrip c
where a.id=b.id
and a.id=c.id
group by a.id,a.name,c.code
    having count(*) >1;

count()广告group by如何运作的一个小例子:

create table testGroup(a, b, c) as ( 
select 1, 2, 3 from dual union all
select 1, 2, 3 from dual union all
select 5, 6, 7 from dual union all
select 5, 6, 7 from dual union all
select 5, 6, 9 from dual union all
select 1, 2, 9 from dual 
)

您需要在群组中使用的列数不会影响您使用计数的方式;说你需要按3列分组:

SQL> select a, b, c, count(*)
  2  from testGroup
  3  group by a, b, c
  4  having count(*) > 1;

         A          B          C   COUNT(*)
---------- ---------- ---------- ----------
         5          6          7          2
         1          2          3          2

如果您只需要汇总2列:

SQL> select a, b, count(*)
  2  from testGroup
  3  group by a, b
  4  having count(*) > 1;

         A          B   COUNT(*)
---------- ---------- ----------
         5          6          3
         1          2          3

这假设您需要计算行数,无论值是否为空。

答案 2 :(得分:-2)

试试这个:

SELECT a.id, a.name, c.code, a.active_dt, a.inactive_dt, b.category, 
       count(DISTINCT a.id,a.name,c.code) [count]
FROM student a
INNER JOIN class b
    ON a.id=b.id
INNER JOIN descrip c
    ON a.id=c.id
GROUP BY a.id, a.name, c.code, a.active_dt, a.inactive_dt, b.category
HAVING count(a.id,a.name,c.code) > 1