限制查询中的记录

时间:2013-08-28 11:16:07

标签: sql-server tsql

这是我的查询

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

以上两个结果对我来说都没问题,如你所见,它们都是真实的记录(正如你在第一个查询中看到的那样)

那么,我怎样才能得到这个结果呢?最快的方法是什么?有什么建议吗?

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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]

答案 2 :(得分:0)

以下是我的想法。 Row_Number函数将为partition 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