我有一张存储学生工作信息的表格。我需要根据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个季度时,这种方法很完美,但是我遇到了所有季度的问题。
第二轮编辑: 我想它是以一种相当懒惰的方式做的:
我刚为特定学生选择了所有小时和季度ID。然后跑了一会儿(odbc_fetch_row())。如果它是201101我将它添加到$ q1堆,201102添加到$ q2堆,依此类推。处理速度有点慢,但对我正在做的事情来说不是一个大问题。
答案 0 :(得分:1)
尝试在查询中使用SELECT TOP 1
或LIMIT 1
,具体取决于您正在运行的SQL。
修改强> 另外,你为什么要努力完成?这看起来很笨重,而且根据您的预期目的,可能有更好的方法。
答案 1 :(得分:1)
我不确定你的目标是什么......
也许你真正想要的是:
select quarterID, sum(hours)
from clinicalStudents
where studentID='$studentID'
group by 1
答案 2 :(得分:0)
SELECT
hours, SUBSTR(quarterId, 4, 2)
FROM
clinicalStudents
WHERE
quarterID IN ('201101', '201102', '201103', '201104') and studentID='$studentID'
根据您使用的数据库,您必须更改SUBSTR函数
答案 3 :(得分: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'
答案 4 :(得分: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;