3

これは私のクエリです

SELECT 
  [MO].[Id] AS [ObjectId],
  [CA].[Id] As [CategoryId],
  [GR].[Id] AS [GroupId]
FROM [MYOBJECT] AZ [MO]
INNER JOIN [Category] AS [CA] ON [CA].[Id] = [MO].[CategoryId]
Inner Join [Group] AS [GR] ON [GR].[CategoryId] = [CA].[ID]

結果は次のとおりです。

ObjectId    CategoryId   GroupId
-----------------------------------
1             1           1
1             2           2
2             1           1
2             2           2

しかし、私はObjectId次のようなものが必要です:categoryidgroupid

 ObjectId    CategoryId   GroupId
-----------------------------------
1             1           1
2             1           1

または

ObjectId    CategoryId   GroupId
-----------------------------------
1             2           2
2             1           1

上記の結果はどちらも私にとっては問題ありません。ご覧のとおり、どちらも実際の記録です(最初のクエリでわかるように)

では、どうすればこの結果を得ることができるでしょうか。これを行う最速の方法は何ですか?なにか提案を?

4

3 に答える 3

4

GROUP BY他の列でいくつかの集計関数を使用および使用します。

SELECT 
  [MO].[Id] AS [ObjectId],
  MIN([CA].[Id]) As [CategoryId],
  MIN([GR].[Id]) AS [GroupId]
FROM [MYOBJECT] AZ [MO]
INNER JOIN [Category] AS [CA] ON [CA].[Id] = [MO].[CategoryId]
Inner Join [Group] AS [GR] ON [GR].[CategoryId] = [CA].[ID]
GROUP BY [MO].[Id]
于 2013-08-28T11:22:45.570 に答える
2

これを試して

;WITH cte AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY [MO].[Id] ORDER BY [CA].[Id]) As rno
  [MO].[Id] AS [ObjectId],
  [CA].[Id] As [CategoryId],
  [GR].[Id] AS [GroupId]
FROM [MYOBJECT] AZ [MO]
INNER JOIN [Category] AS [CA] ON [CA].[Id] = [MO].[CategoryId]
INNER JOIN [Group] AS [GR] ON [GR].[CategoryId] = [CA].[ID]
)

SELECT * 
FROM cte WHERE rno=1

または、CategoryId と GroupId は重要ではないため、このように使用できます

SELECT 
  [MO].[Id] AS [ObjectId],
  MAX([CA].[Id]) As [CategoryId],
  MAX([GR].[Id]) AS [GroupId]
FROM [MYOBJECT] AZ [MO]
INNER JOIN [Category] AS [CA] ON [CA].[Id] = [MO].[CategoryId]
INNER JOIN [Group] AS [GR] ON [GR].[CategoryId] = [CA].[ID]
GROUP BY  [MO].[Id]
于 2013-08-28T11:20:26.630 に答える