这是我昨天SQL joining dilemma的延续......
我有以下表格:
(Student)
| ID | NAME |
| 1234 | dave |
(Assessment)
| ID | DATE | STUDENT_ID | TYPE |
| 1 | 02/03/11 | 1234 | School |
| 2 | 05/03/11 | 1234 | Parent |
(Concern)
| ID | ASSESSMENT_ID | TOPIC | LEVEL | TOPIC_NUMBER |
| 1 | 1 | apple | 3 | 1 |
| 2 | 1 | pears | 2 | 2 |
| 3 | 2 | mango | 2 | 1 |
| 4 | 2 | dates | 4 | 2 |
我想创建一个结合评估和关注点的行:
| StudentId | TIoC1 | TIoC2 | TIoCScore1 | TIoCScore2 | PIoC1 | PIoC2 | PIoCScore1 | PIoCScore2 |
| 1234 | apple | pears | 3 | 2 | mango | dates | 2 | 4 |
这将导出到stats包,因此结构必须保持原样。
这是我现在拥有的SQL:
SELECT a_assessment.StudentId,
TIoC1,TIoC2,TIoCScore1,TIoCScore2,PIoC1,PIoC2,PIoCScore1,PIoCScore2
FROM
dbo.Assessment a_assessment
LEFT OUTER JOIN
(
SELECT P.StudentId, C1.Topic AS TIoC1, C2.Topic AS TIoC2, C3.Topic AS TIoC3, C4.Topic AS TIoC4,
C1.Level AS TIoCScore1, C2.Level AS TIoCScore2, C3.Level AS TIoCScore3, C4.Level AS TIoCScore4
FROM dbo.Assessment P
LEFT JOIN Concern C1 ON P.Id = C1.Assessment_Id and C1.TopicNumber = 1
LEFT JOIN Concern C2 ON P.Id = C2.Assessment_Id and C2.TopicNumber = 2
WHERE P.Type = 'School'
) a_school_cons
ON a_school_cons.StudentId = a_assessment.StudentId
LEFT OUTER JOIN
(
SELECT P.StudentId, C1.Topic AS PIoC1, C2.Topic AS PIoC2
C1.Level AS PIoCScore1, C2.Level AS PIoCScore2
FROM dbo.Assessment P
LEFT JOIN Concern C1 ON P.Id = C1.Assessment_Id and C1.TopicNumber = 1
LEFT JOIN Concern C2 ON P.Id = C2.Assessment_Id and C2.TopicNumber = 2
WHERE P.Type = 'Parent'
) a_parent_cons
ON a_parent_cons.StudentId = a_assessment.StudentId
问题是,它返回两个相同的行!
| StudentId | TIoC1 | TIoC2 | TIoCScore1 | TIoCScore2 | PIoC1 | PIoC2 | PIoCScore1 | PIoCScore2 |
| 1234 | apple | pears | 3 | 2 | mango | dates | 2 | 4 |
| 1234 | apple | pears | 3 | 2 | mango | dates | 2 | 4 |
我无法弄清楚如何更新这个只返回一个 - 感谢任何帮助!!
一如既往地谢谢!
答案 0 :(得分:8)
这里不添加简单的DISTINCT
吗?
答案 1 :(得分:2)
而不是FROM Assessment LEFT JOIN...
做FROM Student LEFT JOIN...
。
您只需要StudentID列,但是评估中的2行将返回两行。