我有一张这样的表
col_name col_white col_red col_brown col_yellow col_one col_two ....
col_white 1
col_red 4
col_two 12
....
我必须做一个选择才能得到这个结果:
col_name col_value
col_white 1
col_red 4
col_two 12
列数是动态的。我该怎么办?
由于
答案 0 :(得分:0)
一种方法是
select 'Col_white' as col_name, Col_white from table
union all
select 'Col_red' as col_name, Col_red from table
.
.
select 'Col_two' as col_name, Col_two from table
您可能还需要了解UNPIVOT
答案 1 :(得分:0)
select t.col_name, max(t.col_value)
from
(select col_name, col_value
from yourtable) t
group by t.col_name
答案 2 :(得分:0)
你可以试试这个吗?
SELECT col_name,CASE WHEN col_name = 'col_white' THEN col_white ELSE CASE WHEN col_name = 'col_red' THEN col_red ELSE CASE WHEN col_name = 'col_two' THEN col_two END
END END AS test FROM dbo.Table_1
答案 3 :(得分:0)
我认为动态sql是这种方式。
DECLARE @SQL AS NVARCHAR(1024)
DECLARE @COL AS NVARCHAR(255)
DECLARE CUR CURSOR FAST_FORWARD FOR
SELECT t.col_name
FROM mytable t
CREATE TABLE #TempTable(
col_name varchar(50),
col_value varchar(50))
OPEN CUR
FETCH NEXT FROM CUR INTO @COL
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @SQL = 'INSERT INTO #TempTable SELECT COL_NAME,'+@COL+' FROM mytable where col_name='''+@COL+''''
EXEC (@SQL)
FETCH NEXT FROM CUR INTO @COL
END
CLOSE CUR;
DEALLOCATE CUR;
SELECT * FROM #TempTable
DROP TABLE #TempTable