在一个字段上选择“不同查询”

时间:2014-01-30 08:40:57

标签: sql sql-server tsql sql-server-2008-r2

这是我的选择查询:

SELECT 
[T1].[Id], [T2].[Id] , [T3].[Id] 
FROM  [T1]
INNER JOIN [T2] On [T1].[Id] = [T2].[T1Id]
INNER JOIN [T3] On [T2].[Id] = [T3].[T2Id]

结果是:

1  1  1
1  2  2
1  2  3
2  3  4
2  3  5
3  4  1

但我需要的是[T1].[Id]这样的东西:

1  1  1
2  3  4
3  4  1

这个ID返回的第一条记录并不重要,所以结果可能是:

1  2  2
2  3  4
3  4  1

但重要的是每条记录的列都有逻辑关系,因此我无法使用MinMax函数。我认为第一个解决方案是将值插入临时表并删除重复项。

但我认为这一定是更好的方法吗?选择查询中的内容。

有没有人对此有任何想法?

2 个答案:

答案 0 :(得分:1)

;with a as
(
SELECT 
[T1].[Id] ID1, [T2].[Id] ID2, [T3].[Id] ID3, 
  row_number() over (partition by [T1].[Id] order by newid()) rn
FROM  [T1]
INNER JOIN [T2] On [T1].[Id] = [T2].[T1Id]
INNER JOIN [T3] On [T2].[Id] = [T3].[T2Id]
)
SELECT ID1, ID2, ID3
FROM a
WHERE rn = 1

答案 1 :(得分:1)

试试这个: -

 Select 
 ID1,ID2,ID3
 from 
 (
   SELECT 
        [T1].[Id], [T2].[Id] , [T3].[Id] ,
        rn = ROW_NUMBER() OVER(partition by [T1].[ID] order by [T1].[ID])
   FROM  [T1]
   INNER JOIN [T2] On [T1].[Id] = [T2].[T1Id]
   INNER JOIN [T3] On [T2].[Id] = [T3].[T2Id]
)a
where a.rn = 1