0

我有一个存储一些学生工作信息的表。我需要根据 studentID 和季度 ID 选择小时数。这是我所拥有的:

SELECT
(SELECT hours FROM clinicalStudents WHERE quarterID='201101' and studentID='$studentID') as q1,             
(SELECT hours FROM clinicalStudents WHERE quarterID='201102' and studentID='$studentID') as q2,             
(SELECT hours FROM clinicalStudents WHERE quarterID='201103' and studentID='$studentID') as q3,             
(SELECT hours FROM clinicalStudents WHERE quarterID='201104' and studentID='$studentID') as q4

它只给了我一些数字,但不是全部。我在我的服务器管理器中运行了这个(减去 WHERE 子句)并收到一个错误:

“子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的”

任何帮助都会很棒。谢谢!

编辑:

$studentID 是在 while 循环中生成的,因此我在转到下一个学生之前使用该学生的小时数。我在每个季度为一个学生获取所有时间,添加它们(这必须在 sql 之外完成),将结果存储在一个变量中,然后转移到下一个学生。当我得到 1 个季度时,这很有效,但我在得到所有季度时遇到问题。

编辑第 2 轮:我想是以一种相当懒惰的方式做到的:

我刚刚为特定学生选择了所有时间和季度 ID。然后跑了一会儿(odbc_fetch_row())。如果是 201101,我将其添加到 $q1 堆中,201102 添加到 $q2 堆中,依此类推。处理速度有点慢,但对我正在做的事情来说不是一个大问题。

4

5 回答 5

1

我不确定你的目标是什么...

也许你真正想要的是:

select quarterID, sum(hours) 
from clinicalStudents 
where studentID='$studentID' 
group by 1
于 2010-12-08T20:29:21.230 回答
1

尝试在查询中使用 aSELECT TOP 1或 a LIMIT 1,具体取决于您正在运行的 sql。

编辑 另外,你为什么要完成?这看起来很笨拙,并且根据您的预期目的,可能有更好的方法可用。

于 2010-12-08T20:23:52.040 回答
0

循环编辑

不要使用循环进行 SUM 运算。而是使用 SUM 聚合操作

允许您将每个季度投影到每一列。

   SELECT
 cs.studentid , q1.hours Q1, q2.hours Q2, q3.hours Q3, q4.hours Q4
    FROM 
    clinicalStudents cs
    (SELECT SUM(hours) hours , studentID 
     FROM clinicalStudents 
     WHERE quarterID='201101' and studentID='$studentID' 
     GROUP BY studentID ) q1
    LEFT join on cs.studentID = q1.clinicalStudents 
    (SELECT SUM(hours) hours , studentID  
     FROM clinicalStudents WHERE quarterID='201102' and studentID='$studentID' 
    GROUP BY studentID )  q2
    LEFT join on cs.studentID = q2.clinicalStudents              
    (SELECT SUM(hours) hours  , studentID 
     FROM clinicalStudents 
     WHERE quarterID='201103' and studentID='$studentID'
     GROUP BY studentID ) q3             
    LEFT join on cs.studentID = q3.clinicalStudents              
    (SELECT SUM(hours) hours , studentID 
     FROM clinicalStudents 
     WHERE quarterID='201104' and studentID='$studentID' GROUP BY studentID ) q4
    LEFT join on cs.studentID = q4.clinicalStudents          
    WHERE cs.studentID='$studentID'
于 2010-12-08T20:30:55.993 回答
0
SELECT 
hours, SUBSTR(quarterId, 4, 2)
FROM 
clinicalStudents 
WHERE 
quarterID IN ('201101', '201102', '201103', '201104') and studentID='$studentID'

根据您使用的数据库,您必须更改函数 SUBSTR

于 2010-12-08T20:27:45.403 回答
0

尝试这个。

select studentID
      ,sum(case when quarterID = '201101' then hours end) as q1
      ,sum(case when quarterID = '201102' then hours end) as q2
      ,sum(case when quarterID = '201103' then hours end) as q3
      ,sum(case when quarterID = '201104' then hours end) as q4
  from clinicalStudents
 where quarterID in('201101', '201102', '201103', '201104')
 group by studentID;
于 2010-12-08T22:07:05.067 回答