1

我说的是 SQL Server 2008。我有三nvarchar列的表。我想在第 N 行选择第一列,从第 M 行选择第二列,从第 K 行选择第三列,其中 M,N,K 彼此不相等。

如何编写这样的查询?也可以选择随机行吗?

4

2 回答 2

3

您可以使用带有ROW_NUMBER()函数的 CTE 来实现此目的:

;WITH CTE AS
(
   SELECT 
      Column1, Column2, Column3,
      (your list of additional columns - if needed),
      RN = ROW_NUMBER() OVER (ORDER BY InsertionDate)
)
SELECT 
    FirstValue = (SELECT Column1 FROM CTE WHERE RN = N),
    SecondValue = (SELECT Column2 FROM CTE WHERE RN = M),
    ThirdValue = (SELECT Column3 FROM CTE WHERE RN = K)

您需要N, M, K在此查询中将 替换为实际的整数值 - 或定义 SQL 变量来保存这三个值。

于 2012-08-24T10:49:20.290 回答
0
declare @i1 int;
declare @i2 int;
declare @i3 int;
SET @i1=2;
SET @i2=4;
SET @i3=1;

;with t1 as
(
select *,row_number() over(order by (select 0)) as rn  from t
)
 select max(CASE rn WHEN @i1 then N1 else '' end),
        max(CASE rn WHEN @i2 then N2 else '' end),
        max(CASE rn WHEN @i3 then N3 else '' end)
        from t1 where rn in (@i1,@i2,@i3);
于 2012-08-24T10:57:07.127 回答