column having maximum integer value from table sql server

喜欢而已 提交于 2019-12-23 05:26:52

问题


This query returns me the maximum integer value from a table:

  SELECT rownum, max(col) as maxValue -- min 10717 , max = 311216
 FROM
  (
   SELECT rownum, col FROM Tables1
    UNPIVOT
   (col FOR ListofColumns IN 

  (col1,col2,col3,col4,col5, col6))
   AS unpivott) AS p
GROUP BY rownum

Instead of "col1,col2,col3,col4,col5,col6". I would like to make this dynamic(automatically taken from table having data type int/numeric).

Note: Sometimes number of columns could be 50 and I don't want to write each and every column names.

How can I do this?


回答1:


Dynamic sql is the only way. you start like this,

    create  table t1(rolname varchar(20),col1 int,col2 int,col3 int,col4 int)
insert into t1 values('a',32,45,23,645)
,('b',67,34,2673,344),('c',423,767,54,343),('d',676,43435,3432,4343)


declare @col varchar(2000)
select top 1
@col=stuff((select ','+'['+COLUMN_NAME+']' from INFORMATION_SCHEMA.COLUMNS b
where TABLE_NAME=a.TABLE_NAME and  DATA_TYPE='int'  for XML path('') ),1,1,'')
from INFORMATION_SCHEMA.COLUMNS a
where TABLE_NAME='t1'

select @col

declare @sql varchar(max)
set @sql='sELECT rolname, max(col)col
 FROM
  (
   SELECT * FROM t1
    UNPIVOT
   (col FOR ListofColumns IN 

  ( '+@col+'))
   AS unpivott) AS p
   GROUP BY rolname'

   exec (@sql)


来源:https://stackoverflow.com/questions/43585733/column-having-maximum-integer-value-from-table-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!