2012-11-15 175 views
1

我有一個表,看起來像這樣,讓我們​​稱這個表B交叉連接兩個表

id boardid schoolid  subject  cnt1 cnt2 cnt3 .... 
================================================================= 
1  20   21   f  
2  20   21   r 
3  20   21   w 
4  20   21   m 
5  20   30   r 
6  20   30   w 
7  20   30   m 

假設計數只是整數。請注意0​​沒有subject = f。同樣,對於大多數學校而言,存在一些dosnt。您可能有剛剛r, w一個schoolid或一些只是r, m, f ..

所以我想要做的是爲每個學校4個一致行,那dosnt行存在我想虛值。我想創建一個輔助表

drop table #A 
Select * into #A FROM 
(
select [subject_s] = 'r', orderNo = 1 
union all 
select [subject_s] = 'w', orderNo = 2 
union all 
select [subject_s] = 'm', orderNo = 3 
union all 
select [subject_s] = 'f', orderNo = 4 
) z 

並做了一些加入他們,但我沒有得到的地方。我嘗試了內部連接,留下了外部連接,交叉連接,一切。我甚至試圖製作笛卡爾產品。我認爲我的笛卡爾產品混亂了,因爲我有orderno,所以它在主表中每行產生16行。實際上輸入這個,我意識到如果我刪除orderno,應用笛卡爾產品,然後在後面添加orderno,它可能會工作,但我有興趣看看你們能想出什麼。我很難過。

最終結果

id boardid schoolid  subject  cnt1 cnt2 cnt3 .... 
================================================================= 
1  20   21   r  
2  20   21   w 
3  20   21   m 
4  20   21   f 
5  20   30   r 
6  20   30   w 
7  20   30   m 
7  20   30   f 
+0

你有一張桌子,所有科目?你如何確定每個學校需要出現的所有科目? –

+1

您使用的是什麼RDBMS?爲什麼最終結果的最後一行的id是7? – Lamak

+0

Typo,id是一個自動生成的數字。並且我創建了一個臨時表將所有我的主題(只有四個) – masfenix

回答

1

嘗試以下操作:

SELECT S.boardid, S.schoolid, A.[subject], B.cnt1, B.cnt2, B.cnt3 
FROM (SELECT DISTINCT boardid, schoolid FROM YourTable) S 
CROSS JOIN #A A 
LEFT JOIN YourTable B 
    ON B.boardid = S.boardid AND B.schoolid = S.schoolid 
    AND A.[subject] = B.[subject] 
-1

我會使用:

SELECT 
    boardid, schoolid, dist_subject, id, cnt1, ... 
FROM 
    (SELECT 
     boardid, schoolid, dist_subject 
    FROM 
     (SELECT 
      DISTINCT subject AS dist_subject 
     FROM b) s full outer join 
     (SELECT 
      boardid, schoolid 
     FROM b 
     GROUP BY 
      boardid, schoolid ) g) sg LEFT OUTER JOIN 
    b ON 
    sg.boardID = b.boardID AND 
    sg.schoolid = b.schoolID 
    sg.dist_subject = b.subject 
+0

永遠不要使用implioct連接。他們是SQl反模式。改爲使用交叉連接,然後維護腳本的人就會知道這不是偶然的交叉連接,而是預期的交叉連接。 – HLGEM

0

因爲我不知道你正在使用我試過這RDBMS以下與sqlite和更簡單的表格:

sqlite> create table schools (name varchar, subject varchar, teacher varchar); 

sqlite> select * from schools; 
School1|Maths|Mr Smith 
School2|English|Jack 
School3|English|Jimmy 
School3|Maths|Jane 
School4|Computer Science|Bob 

sqlite> select 
      schoolnames.name, 
      subjects.subject, 
      ifnull(teachers.teacher, "Unknown") 
     from (select distinct name from schools) schoolnames 
     join (select distinct subject from schools) subjects 
     left join schools teachers 
      on schoolnames.name = teachers.name 
       and subjects.subject = teachers.subject; 

School1|Maths|Mr Smith 
School1|English|Unknown 
School1|Computer Science|Unknown 

School2|Maths|Unknown 
School2|English|Jack 
School2|Computer Science|Unknown 

School3|Maths|Jane 
School3|English|Jimmy 
School3|Computer Science|Unknown 

School4|Maths|Unknown 
School4|English|Unknown 
School4|Computer Science|Bob