2011-02-03 96 views
1

這是SQL joining dilemma我昨天的延續......SQL JOIN返回行太多,

我有以下表格:

(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 | 

這是要出口到一個統計包,所以該結構具有保持原樣。

這是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

你也可以看看我提供的原始問題的答案的編輯版本。編輯答案時可能沒有通知發送給OP,因此您剛剛錯過了答案。 – 2011-02-04 08:48:07

+0

謝謝Andriy,我沒有得到通知。我會在今天測試你的分組建議 - 謝謝你的幫助! – laura 2011-02-04 10:10:28

回答

8

在此處不添加簡單的DISTINCT工作?

+0

是的!我一直在看這個太久了 - 不敢相信我沒有想到 - 非常感謝你! – laura 2011-02-03 12:36:41

2

而不是FROM Assessment LEFT JOIN...FROM Student LEFT JOIN...

您只需要StudentID列,但評估中的2行會重新調整兩行。