我需要一次获得16列的最小值。
即。 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
minimum = 1
我需要这个为一个新的16组滑过1,并获得那个的最小值
即。 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
最低2
有2571列,11,000行。
到目前为止,我从以下行获取行:
DECLARE @Start INT =1
DECLARE @End INT=16
Begin Transaction
SELECT *
FROM (SELECT Row=Row_number()
OVER (
ORDER BY column_name),
column_name
FROM information_schema.columns
WHERE table_name IN ( '100', '200', '300', '400' )
AND column_name NOT IN ( 'time', 'scan' ))Row
WHERE row >= @start
AND row <= @end
Commit
这给了我前16列,但是在一列中。 我想打开它并将返回的结果放入游标中,我可以执行逐行分析。
像这样的东西,虽然如果我为每个我想要的行号添加1,它应该移动它。
DECLARE @Column01 NVARCHAR(50),
@Column02 NVARCHAR(50),
@Column03 NVARCHAR(50),
@Column04 NVARCHAR(50),
@Column05 NVARCHAR(50),
@Column06 NVARCHAR(50),
@Column07 NVARCHAR(50),
@Column08 NVARCHAR(50),
@Column09 NVARCHAR(50),
@Column10 NVARCHAR(50),
@Column11 NVARCHAR(50),
@Column12 NVARCHAR(50),
@Column13 NVARCHAR(50),
@Column14 NVARCHAR(50),
@Column15 NVARCHAR(50),
@Column16 NVARCHAR(50)
DECLARE @Start INT =1
DECLARE @End INT=16
DECLARE db_cursor CURSOR FOR
SELECT column_name
FROM (SELECT Row=Row_number()
OVER (
ORDER BY column_name),
column_name
FROM information_schema.columns
WHERE table_name IN ( '100', '200', '300', '400' )
AND column_name NOT IN ( 'time', 'scan' ))Row
WHERE row >= @start
AND row <= @end
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @Column01 ,@Column02
WHILE @@FETCH_STATUS = 0
BEGIN
--do work here
print @Column01 + ' ' + @Column02
FETCH NEXT FROM db_cursor INTO @Column01 ,
@Column02
END
CLOSE db_cursor
DEALLOCATE db_cursor
我知道我可以转动它,但是因为我不需要聚合而能够满足我的要求吗?有什么建议吗?
答案 0 :(得分:0)
您不需要动态SQL。只需使用UNPIVOT
标准化您的数据。
WITH t AS (
SELECT row, scan, col, val
FROM MyTable
UNPIVOT(val FOR col IN ([1],[2],[3],[4],...<snip>...,[2570],[2571]))p
)
SELECT
row, scan, col AS range_start, col + 15 AS range_end, min_val
FROM t t1
CROSS APPLY (
SELECT
MIN(t2.val) AS min_val
FROM t
WHERE
row = t1.row AND
scan = t1.scan AND
col BETWEEN t1.col AND t1.col + 15
) t2