我有三个MySql表:
用户:UserId,UserName
测试:TestId,TestName
通过:PassId,UserId,TestId,DateTaken
我想返回一个表格,显示每个用户通过的最新测试的日期,例如
|--------|---------|---------|---------|---------|---------|
|User |Test A |Test B |Test C |Test D |Test E |
|--------|---------|---------|---------|---------|---------|
|James |Null |6/3/11 |Null |Null |4/3/11 |
|Mark |Null |1/4/11 |8/5/11 |23/5/10 |Null |
|--------|---------|---------|---------|---------|---------|
在这个例子中,詹姆斯从未通过测试A,C或D.他可能已经多次参加测试B,但最新的是在6/3/11。
我打算在ASP.NET GridView中显示这些数据。什么是最好的方法 - 可以在SELECT语句中完成吗?请帮忙!
非常感谢提前。
答案 0 :(得分:3)
要实现此目的,您需要为每个测试结果使用子查询 试试这个:
SELECT User,
(SELECT MAX(DateTaken) FROM Passes p INNER JOIN Tests t ON p.TestId=t.TestId WHERE p.UserId=u.UserId AND TestName='Test A') AS 'Test A',
(SELECT MAX(DateTaken) FROM Passes p INNER JOIN Tests t ON p.TestId=t.TestId WHERE p.UserId=u.UserId AND TestName='Test B') AS 'Test B',
(SELECT MAX(DateTaken) FROM Passes p INNER JOIN Tests t ON p.TestId=t.TestId WHERE p.UserId=u.UserId AND TestName='Test C') AS 'Test C',
(SELECT MAX(DateTaken) FROM Passes p INNER JOIN Tests t ON p.TestId=t.TestId WHERE p.UserId=u.UserId AND TestName='Test D') AS 'Test D',
(SELECT MAX(DateTaken) FROM Passes p INNER JOIN Tests t ON p.TestId=t.TestId WHERE p.UserId=u.UserId AND TestName='Test E') AS 'Test E'
FROM Users u
答案 1 :(得分:3)
select
u.username,
max(case when testid = 1 then datetaken else null end) as A,
max(case when testid = 2 then datetaken else null end) as B,
max(case when testid = 3 then datetaken else null end) as C,
max(case when testid = 4 then datetaken else null end) as D,
max(case when testid = 5 then datetaken else null end) as E
from users as u
left join passes as p on u.userid = p.userid
group by u.userid
答案 2 :(得分:2)
这是相当通用的解决方案。 MySQL确实支持我写的所有内容,但是可能有更好的MySQL特定解决方案。
Select
UserName,
Max(TestA) testa,
Max(TestB) testb,
Max(TestC) testc,
Max(TestD) testd,
Max(TestE) teste
FROM
(
SELECT
u.UserName,
Case When TestName = "Test A" then p.DateTaken END TestA,
Case When TestName = "Test B" then p.DateTaken END TestB,
Case When TestName = "Test C" then p.DateTaken END TestC,
Case When TestName = "Test D" then p.DateTaken END TestD,
Case When TestName = "Test E" then p.DateTaken END TestE
FROM
Users u
LEFT JOIN tests t
ON u.UserId = t.userid
LEFT JOIN (SELECT
Max(DateTaken) DateTaken,
userId,
TestId,
FROM
Passes
GROUP BY
userId,
TestId) p
ON t.testId = p.TestId) t
Group BY
UserName