2013-01-03 244 views
-4

我有如下三個表:SQL服務器數查詢

Article 
No Storage_code Type_code 
--- ------------ --------- 
1 10 00 00   S 
2 10 10 00  P 
1 10 10 10  S 
3 11 00 00  C 
1 10 00 00  C 
2 11 10 10  P 

Storage 
Main_Code Division_Code Safe_Code Position_Code Main_Name 
--------- ------------- --------- ------------- ------------- 
10 00 00  10   00 00    Div1 
10 10 00  10   10 00   Div1_Saf1 
10 10 10  10   10 10   Div1_Saf1_Pos1 
10 10 11  10   10 11    Div1_Saf1_Pos2 
10 10 12  10   10 12   Div1_Saf1_Pos3 
10 11 00  10   11 00   Div1_Saf2 
10 11 10  10   11 10   Div1_Saf2_Pos1 
10 11 11  10   11 11    Div1_Saf2_Pos2 
10 11 12  10   11 12    Div1_Saf2_Pos3 
11 00 00  11   00 00    Div2 
11 10 00  11   10 00   Div2_Saf1 
11 10 10  11   10 10   Div2_Saf1_Pos1 
11 10 11  11   10 11   Div2_Saf1_Pos2 
11 10 12  11   10 12   Div2_Saf1_Pos3 
11 11 00  11   11 00   Div2_Saf2 
11 11 10  11   11 10   Div2_Saf2_Pos1 
11 11 11  11   11 11   Div2_Saf2_Pos2 
11 11 12  11   11 12   Div2_Saf2_Pos3 

Types 
Code  Name 
--------  -------- 
C  Cards 
P  Plates 
S  Stickers  

,我想通過一個選擇作爲後續結果:PLZ儘快

Main_Code Division_Code Safe_Code Position_Code Main_Name Cards Plates Stickers Total 
---------------------------------------------------------------------------------------- 
10 00 00   10   00 00 Div1  1 1  2  4 
10 10 00   10   10 00 Div1_Saf1 0 1  1  2 
10 10 10   10   10 10 Div1_Saf1_Pos1 0 0  1  1 
11 00 00   11   00 00 Div2  1 1  0  2 
11 10 00   11   10 00 Div2_Saf1 0 1  0  1 
11 10 10   11   10 10 Div2_Saf1_Pos1 0 1  0  1 

任何一個可以幫助我。

+1

我開始* *在你的問題的編輯,這樣我們就可以看到表。但我不打算全部清理。發佈應該有固定佈局的代碼或項目時,請使用'{}'代碼示例按鈕。並使用預覽區域,以便您可以*看到*您的問題實際上會是什麼樣子。原來的問題是不可讀的。 –

+1

學習SQL加入 – scoota269

+0

您還需要解釋如何計算'Cards','Plates'和'Stickers'列。 –

回答

0

您正在尋找的行旋轉爲列,試試這個:

SELECT 
    s.[Main_Code], 
    s.Division_Code, 
    s.Safe_Code, 
    s.Position_Code, 
    s.Main_Name, 
    SUM(CASE WHEN t.Name ='Cards' THEN 1 ELSE 0 END) AS Cards, 
    SUM(CASE WHEN t.Name ='Plates' THEN 1 ELSE 0 END) AS Plates, 
    SUM(CASE WHEN t.Name ='Stickers' THEN 1 ELSE 0 END) AS Stickers, 
    COUNT(t.Name) AS Total 
FROM Storage s 
INNER JOIN Article a ON a.Storage_code = s.[MainCode] 
INNER JOIN Types t ON a.Type_code = t.Code 
GROUP BY s.Main_Code, 
     s.Division_Code, 
     s.Safe_Code, 
     s.Position_Code, 
     s.Main_Name;