2

次の表を想定します。

グループ: (ID、タイトル): {1,G1}, {2,G2}, {3,G3}, {4, G4}

カテゴリ: (ID、タイトル):{1, Cat1}, {2, Cat2}, {3, Cat3}, {4, Cat4}

製品: (ID、GroupId、CategoryId、名前):

{1, 1, 1, G1C1P1},
{2, 1, 2, G1C2P2},
{3, 1, 2, G1C2P3},
{4, 2, 2, G2C2P4},
{5, 2, 2, G2C2P5},
{6, 3, 1, G3C1P6},
{7, 3, 3, G3C3P7}

だから私が必要とするのは、上記の値のグループごとのカテゴリのカウントは次のとおりです。

Group  Category  Count
----------------------
 G1     Cat1      1
 G1     Cat2      2
 G1     Cat3      0
 G1     Cat4      0
 G2     Cat1      0
 G2     Cat2      2
 G2     Cat3      0
 G2     Cat4      0
 G3     Cat1      1
 G3     Cat2      0
 G3     Cat3      1
 G3     Cat4      0
 G4     Cat1      0
 G4     Cat2      0
 G4     Cat3      0
 G4     Cat4      0

私はこれを試します:

SELECT 
        [GR].[Title] AS [Group],
        COUNT([PR].[Id]) AS [Count],
        [CA].[Title]

FROM [dbo].[Group] AS [GR]
FULL OUTER JOIN [dbo].[Product] AS [PR] ON [GR].[Id] = [PR].[GroupId]
FULL OUTER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]
GROUP BY [CA].[Title], [GR].[Title];
GO

しかし、それは正確なものではないので、あなたの提案は何ですか?

4

2 に答える 2

4

可能なすべてのグループカテゴリの組み合わせを作成するにCROSS JOINは、2つのテーブル(Groupおよび)を作成してから、次のテーブルを作成する必要があります。CategoryLEFT JOINProduct

SELECT 
    gr.Title     AS [Group],
    ca.Title,
    COUNT(pr.Id) AS [Count]
FROM 
        dbo.[Group] AS gr
    CROSS JOIN 
        dbo.Category AS ca 
    LEFT OUTER JOIN 
        dbo.Product AS pr 
            ON  pr.GroupId = gr.Id
            AND pr.CategoryId = ca.Id 
GROUP BY 
    gr.Title,
    ca.Title 
ORDER BY
    gr.Title,
    ca.Title ;

またはこの方法(最初GROUP BYにProductsテーブルで、次に派生テーブルを結合します):

SELECT 
    gr.Title             AS [Group],
    ca.Title,
    COALESCE(pr.cnt, 0)  AS [Count]
FROM 
        dbo.[Group] AS gr
    CROSS JOIN 
        dbo.Category AS ca 
    LEFT OUTER JOIN 
        ( SELECT 
              GroupId,
              CategoryId,
              COUNT(*) AS cnt
          FROM
              dbo.Product 
          GROUP BY 
              GroupId,
              CategoryId
        ) AS pr
            ON  pr.GroupId = gr.Id
            AND pr.CategoryId = ca.Id 
ORDER BY
    gr.Id,
    ca.Id ;

Group(Title)と列が一意である場合Category(Title)、クエリは同等です(順序を除く)。

于 2012-12-09T09:47:42.337 に答える
0

これを試してください:

SELECT 
        [GR].[Title] AS [Group],
        [CA].[Title],
        COUNT([PR].[Id]) AS [Count]

FROM [dbo].[Product] AS [PR]
FULL OUTER JOIN [dbo].[Group] AS [GR] ON [PR].[GroupId] = [GR].[Id]
FULL OUTER JOIN [dbo].[Category] AS [CA] ON [PR].[CategoryId] = [CA].[Id]
GROUP BY [GR].[Title],[CA].[Title];
GO
于 2012-12-09T09:46:29.310 に答える