在Oracle中使用GROUP BY时遇到问题

时间:2014-03-23 14:15:05

标签: sql oracle group-by

我用以下命令创建了一个表。

CREATE TABLE student
(sid int,sname varchar(20), email varchar(25), phone varchar(10),tfee float,feepaid float,course varchar(2),branch varchar(3),city varchar(15));

现在,当我尝试创建静态视图时(对于静态视图,我们需要使用group by子句)。但它给了我一个错误。这是我的查询。

CREATE VIEW sacview as 
SELECT sid,sname,tfee,feepaid,course,branch 
FROM student 
GROUP BY sid;

错误不是按表达式分组。我不知道为什么?一切似乎都适合我。

1 个答案:

答案 0 :(得分:3)

据推测,sid已经是* unique in the student`表。所以,这可能是你想要的:

CREATE VIEW sacview as 
    SELECT sid, sname, tfee, feepaid, course, branch 
    FROM student ;

如果您担心重复(可能表明存在其他问题),可以使用distinct

CREATE VIEW sacview as 
    SELECT DISTINT sid, sname, tfee, feepaid, course, branch 
    FROM student ;

group by sid的问题是select中的其余列。假设sid确实是唯一的,那么ANSI标准的更新版本支持您的语法,但Oracle(以及大多数其他数据库)不实现此功能。你可以做你正在尝试的事情:

CREATE VIEW sacview as 
    SELECT sid, sname, tfee, feepaid, course, branch 
    FROM student
    GROUP BY sid, sname, tfee, feepaid, course, branch ;

但是distinct做了同样的事情。

编辑:

您可以使用sid每个row_number()选择一个任意行:

CREATE VIEW sacview as 
    SELECT sid, sname, tfee, feepaid, course, branch 
    FROM (SELECT s.*, ROW_NUMBER() OVER (PARTITION BY sid ORDER BY sid) as seqnum
          FROM student
         ) t
    WHERE seqnum = 1 ;