2013-08-28 133 views
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

使用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] 
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 

或者你可以用這樣的,因爲類別ID和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] 
0

這是我想到的。 Row_Number函數將爲分區的by子句中的每一行發出一個自動遞增的數字,在這種情況下爲ObjectId或MO.Id。然後在外部選擇中,我們返回其他列並通過新的RowNum列過濾。

SELECT A.ObjectId, 
      A.CategoryId , 
      A.GroupId 
    FROM (
      SELECT 
       [MO].[Id] AS [ObjectId], 
       [CA].[Id] As [CategoryId], 
       [GR].[Id] AS [GroupId], 
       ROW_NUMBER() OVER(PARTITION BY [MO].[Id]) AS RowNum 
      FROM [MYOBJECT] AZ [MO] 
      INNER JOIN [Category] AS [CA] ON [CA].[Id] = [MO].[CategoryId] 
      INNER JOIN [Group] AS [GR] ON [GR].[CategoryId] = [CA].[ID] 
     ) A 
    WHERE A.RowNum = 1