-4

私は以下のように3つのテーブルを持っています:

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    

そして、次のように1つの選択で結果が必要です:

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

できるだけ早く私を助けてくれませんか。

4

1 に答える 1

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;
于 2013-01-03T08:03:25.713 に答える