0

我有一张这样的桌子

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

列数是动态的。我该怎么做?

谢谢

4

4 回答 4

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
于 2013-09-17T07:42:24.687 回答
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
于 2013-09-17T07:25:58.527 回答
0
select t.col_name, max(t.col_value)
from
(select col_name, col_value
from yourtable) t
group by t.col_name
于 2013-09-17T07:03:43.503 回答
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

于 2013-09-17T06:59:20.573 回答