好吧,我不像我应该的那样精通 SQL,但我熟悉 Joins、Unions 等的工作原理,我只是想不出一个解决方案。我试图从两个不同的表中获取数据,但猴子扳手是右侧表的行数可能比我在结果集中实际想要的行数多。我必须加入这两个表的唯一条件是电子邮件地址。这是代码:
CREATE TABLE #PPEInfo(StudentEmail nvarchar(128), StudentName nvarchar(128), DevUnits int)
INSERT INTO #PPEInfo (StudentEmail, DevUnits)
SELECT e.StudentEmail AS Email, sum(ck.DevelopmentUnits) AS DevUnits
FROM Enrollments e, CourseKeys ck
WHERE e.CertGenerated = 'true'
AND e.CourseId = ck.CourseId
GROUP BY e.StudentEmail
ORDER BY DevUnits DESC
SELECT p.StudentEmail, p.DevUnits, s.StudentName
FROM #PPEInfo p
RIGHT OUTER JOIN Surveys s
ON p.StudentEmail = s.StudentEmail
ORDER BY DevUnits DESC, StudentName ASC
DROP TABLE #PPEInfo
问题是我收到了多个学生姓名,因为他们在提交时可能没有使用同一个。例如:
Email Address James R. Salvati
Email Address James Salvati
我想出的唯一解决方案是先用电子邮件地址填充我的临时表,然后使用“TOP(1)”在“调查”表中查询姓名,只得到一个学生姓名。它确实有效,但它非常占用 CPU,而且我正在处理大量记录。这是代码(尽管此时我并不关心 DevUnits 只是想提出一些建议):
CREATE TABLE #PPEInfo(ID int IDENTITY(1,1), StudentEmail nvarchar(128), StudentName nvarchar(128), DevUnits int)
INSERT INTO #PPEInfo (StudentEmail)
SELECT DISTINCT StudentEmail FROM Enrollments
WHERE CertGenerated = 'true'
DECLARE @rowID int
DECLARE @email nvarchar(128)
SET @rowID = (SELECT max(ID) FROM #PPEInfo)
WHILE (@rowID > 0)
BEGIN
SET @email = (SELECT StudentEmail FROM #PPEInfo WHERE ID = @rowID)
UPDATE #PPEInfo
SET StudentName = (SELECT TOP(1) s.StudentName FROM Surveys s
WHERE s.StudentEmail = @email)
WHERE ID = @rowID
SET @rowID = @rowID - 1
END
SELECT * FROM #PPEInfo
ORDER BY DevUnits DESC
DROP TABLE #PPEInfo
我从来不需要在其中一个板上发帖。我通常会找到解决方案或想出一个解决方案,但这个解决方案超出了我的 SQL 能力。
谢谢!!!