3

我正在尝试列出研究生成员多于本科生成员的群体。我觉得我的想法背后有这个概念,但是进行查询比简单的翻译要困难一些。下面是我的代码,我目前在 COUNT(student.career = 'GRD') 处出现缺少右括号的错误。谢谢。

SELECT studentgroup.name 
COUNT(student.career = 'GRD') - COUNT(student.career = 'UGRD') 
AS Gradnum FROM studentgroup 
INNER JOIN memberof ON studentgroup.GID = memberof.GroupID
INNER JOIN student ON memberof.StudentID = student.SID
WHERE Gradnum > 1;
4

4 回答 4

1
SELECT studentgroup.name 
SUM(CASE WHEN student.career = 'GRD' THEN 1 ELSE 0 END) - SUM(CASE WHEN student.career = 'UGRD' THEN 1 ELSE 0 END) 
AS Gradnum FROM studentgroup 
INNER JOIN memberof ON studentgroup.GID = memberof.GroupID
INNER JOIN student ON memberof.StudentID = student.SID
WHERE Gradnum > 1
GROUP BY studentgroup.name;
于 2013-04-25T04:41:09.267 回答
1
SELECT studentgroup.GID, max(studentgroup.name)
FROM studentgroup 
INNER JOIN memberof ON studentgroup.GID = memberof.GroupID
INNER JOIN student ON memberof.StudentID = student.SID
GROUP BY studentgroup.GID
HAVING SUM(CASE WHEN student.career = 'GRD' THEN 1 
                WHEN student.career = 'UGRD'THEN -1
                ELSE 0
            END) >0
于 2013-04-25T06:24:00.030 回答
0

我使用了 WITH As 子句,大多数 DBMS 都支持,比如 SQL Server、PostGresSQL,除了 MySQL

With grpTbl As
(

SELECT studentgroup.name As StudentGroupName,
       SUM( CASE WHEN student.career = 'GRD' THEN 1 ELSE 0 END ) AS 'TotalGraduate',
       SUM( CASE WHEN student.career = 'UGRD' THEN 1 ELSE 0 END ) AS 'TotalUnderGraduate'

FROM studentgroup 
INNER JOIN memberof ON studentgroup.GID = memberof.GroupID
INNER JOIN student ON memberof.StudentID = student.SID

)


SELECT StudentGroupName
FROM grpTbl 
WHERE TotalGraduate > TotalUnderGraduate

WHERE对于 MySQL,您可以使用临时表来存储 First 查询的结果集,并过滤掉在子句中的毕业生多于 UnderGraduate 的 GroupNames 。此方法适用于其他 DBMS,不同之处在于创建临时表的语法。

CREATE TEMPORARY TABLE grpTbl (
StudentGroupName varchar(255),
TotalGraduate INT,
TotalUnderGraduate INT
);


INSERT INTO grpTbl
SELECT studentgroup.name As StudentGroupName,
           SUM( CASE WHEN student.career = 'GRD' THEN 1 ELSE 0 END ) ,
           SUM( CASE WHEN student.career = 'UGRD' THEN 1 ELSE 0 END ) 

    FROM studentgroup 
    INNER JOIN memberof ON studentgroup.GID = memberof.GroupID
    INNER JOIN student ON memberof.StudentID = student.SID 


 SELECT StudentGroupName
    FROM grpTbl 
    WHERE TotalGraduate > TotalUnderGraduate


 DROP TABLE grpTbl 
于 2013-04-25T06:00:31.757 回答
0

另一种选择

SELECT studentgroup.name
FROM studentgroup INNER JOIN memberof ON studentgroup.GID = memberof.GroupID
                  INNER JOIN student ON memberof.StudentID = student.SID
GROUP BY studentgroup.name
HAVING COUNT(CASE WHEN student.career = 'GRD' THEN student.career END) 
         > COUNT(CASE WHEN student.career = 'UGRD' THEN student.career END)
于 2013-04-25T06:45:19.330 回答