查询:
SELECT sd.ident,sd.suniq, testc, subtestc, ts.testscore,
metadept, ts.takendt,
MAX(takendt) testdate
FROM studemo sd, stutests ts, testdef td, udefstu ud
WHERE ts.suniq =sd.suniq
AND td.testuniq = ts.testuniq
AND ts.suniq = ud.suniq
AND td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
GROUP BY sd.suniq
ORDER BY suniq
收到以下错误:
Msg 8120,Level 16,State 1,Line 2 列'studemo.ident'无效 选择列表,因为它不是 包含在一个聚合中 函数或GROUP BY子句。
我的目标是获得最新的考试成绩。我成功了,直到我尝试添加更多表格以包含更多学生信息。
答案 0 :(得分:5)
您需要将那些不在聚合函数中的列添加到GROUP BY
中,以使SQL语句有效。
GROUP BY sd.ident,sd.suniq, testc, subtestc, ts.testscore, metadept, ts.takendt
答案 1 :(得分:3)
select sd.ident,sd.suniq, testc, subtestc, ts.testscore, metadept, ts.takendt, max(takendt)testdate
from studemo sd, stutests ts, testdef td, udefstu ud
where ts.suniq =sd.suniq
and td.testuniq = ts.testuniq
and ts.suniq = ud.suniq
and td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
group by sd.ident,sd.suniq, testc, subtestc, ts.testscore, metadept, ts.takendt
order by suniq
评论:上面的代码是@Neil的意思
答案 2 :(得分:3)
我怀疑你想要显示每个学生的最大门数,即使他们已经进行了多次测试,例如如果他们已经进行了两次测试,那么你想要显示两个测试日期,并且每行显示最大日期。如果是这种情况,那么按所有其他列进行分组将无济于事。也许尝试这个,假设SQL Server 2005或更高版本:
WITH md AS
(
SELECT ts.suniq, maxdate = MAX(ts.takendt)
FROM dbo.stutests AS ts
INNER JOIN
dbo.testdef AS td
ON td.testuniq = ts.testuniq
WHERE
td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
GROUP BY ts.suniq
)
SELECT
sd.ident,
sd.suniq,
testc, -- which table does this come from? why no prefix?
subtestc, -- which table does this come from? why no prefix?
ts.testscore,
metadept, -- which table does this come from? why no prefix?
ts.takendt,
md.maxdate
FROM
dbo.studemo AS sd
INNER JOIN
dbo.stutests AS ts
ON sd.suniq = ts.suniq
INNER JOIN
dbo.testdef AS td
ON td.testuniq = ts.testuniq
INNER JOIN
dbo.udefstu AS ud
ON ts.suniq = ud.suniq
INNER JOIN md
ON md.suniq = sd.suniq
WHERE
td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
ORDER BY
sd.suniq; -- you forgot a prefix here too
-- could cause problems if you change the query later
答案 3 :(得分:2)
您需要将不使用聚合函数的剩余字段添加到Group By
。
select sd.ident,sd.suniq, testc, subtestc, ts.testscore, metadept, ts.takendt, max(takendt)testdate
from studemo sd, stutests ts, testdef td, udefstu ud
where ts.suniq =sd.suniq
and td.testuniq = ts.testuniq
and ts.suniq = ud.suniq
and td.testuniq IN ('2000089', '2000090', '2000091', '2000092')
group by sd.suniq, sd.ident, testc, subtestc, ts.testscore, metadept, ts.takendt
order by suniq