我有一张表,最多可以有5行,最少1行。现在我需要将这些行存储在不同的变量中,如@v1,@v2,@v3,@v4,@v5
。我该怎么办?
该表只有1列custid
。
CustId
100
200
300
400
如果表格只包含1行,则@v1
应该包含该值,其余值可以为null
。
答案 0 :(得分:9)
您可以使用以下查询:
SELECT @v1 = MAX(CASE WHEN rn = 1 THEN CustId END),
@v2 = MAX(CASE WHEN rn = 2 THEN CustId END),
@v3 = MAX(CASE WHEN rn = 3 THEN CustId END),
@v4 = MAX(CASE WHEN rn = 4 THEN CustId END),
@v5 = MAX(CASE WHEN rn = 5 THEN CustId END)
FROM (
SELECT CustId, ROW_NUMBER() OVER (ORDER BY CustId) AS rn
FROM mytable ) t
使用ROW_NUMBER
为表的每条记录指定一个不同的数字。然后,在外部查询中使用条件聚合,您可以使用此数字来设置每个单独的变量。
如果少于5行,相应的变量将设置为NULL
。
答案 1 :(得分:5)
如果您有SQL Server 2012或更高版本,则可以尝试LAG()功能。
SELECT
@v1 = custID
, @v2 = LAG(custID, 1) OVER (ORDER BY custID DESC)
, @v3 = LAG(custID, 2) OVER (ORDER BY custID DESC)
, @v4 = LAG(custID, 3) OVER (ORDER BY custID DESC)
, @v5 = LAG(custID, 4) OVER (ORDER BY custID DESC)
FROM yourTable
ORDER BY CustID DESC
答案 2 :(得分:1)
试试这个..
create table #tab
(
custID int
)
insert into #tab
select 110 union all
select 120 union all
select 130 union all
select 140 union all
select 150
declare @v1 int,@v2 int, @v3 int, @v4 int, @v5 int
select @v1 = custID
from #tab
order by custid
OFFSET 0 row
FETCH NEXT 1 ROW ONLY
select @v2 = custID
from #tab
order by custid
OFFSET 1 row
FETCH NEXT 1 ROW ONLY
select @v3 = custID
from #tab
order by custid
OFFSET 2 row
FETCH NEXT 1 ROW ONLY
select @v4 = custID
from #tab
order by custid
OFFSET 3 row
FETCH NEXT 1 ROW ONLY
select @v5 = custID
from #tab
order by custid
OFFSET 4 row
FETCH NEXT 1 ROW ONLY
select @v1,@v2,@v3,@v4,@v5
答案 3 :(得分:1)
即使使用 PIVOT 功能并使用帮助 Row_number
,我们也可以实现这一目标declare @mytable table (CustId int)
insert into @mytable values
(100), (200), (300), (400),(500)
SELECT [1] as V1, [2]as V2, [3]as V3, [4]as V4, [5]as V5
FROM
(SELECT CustId,ROW_NUMBER() OVER (ORDER BY CustId) AS value
FROM @mytable ) AS SourceTable
PIVOT
(
max(CustId)
FOR value IN ([1], [2], [3], [4],[5])
) AS PivotTable
答案 4 :(得分:0)
只是为了好玩,一种野蛮的方法:
Select @v1 = t1.CustID,
@v2 = oa2.CustID,
@v3 = oa3.CustID,
@v4 = oa4.CustID,
@v5 = oa5.CustID
from Table t1
outer apply(select top 1 CustID from Table t2 where t2.CustID not in(t1.CustID) order by CustID) oa2
outer apply(select top 1 CustID from Table t3 where t3.CustID not in(t1.CustID, oa2.CustID) Order by CustID) oa3
outer apply(select top 1 CustID from Table t4 where t4.CustID not in(t1.CustID, oa2.CustID, oa3.CustID) Order by CustID) oa4
outer apply(select top 1 CustID from Table t5 where t5.CustID not in(t1.CustID, oa2.CustID, oa3.CustID, oa4.CustID) Order by CustID) oa5