如何将行转换为列

时间:2017-05-03 00:45:10

标签: sql-server-2008

我在// Android App import io.socket.client.Socket; import io.socket.client.IO; import io.socket.emitter.Emitter; import android.util.Log; public class SocketIO implements Runnable { @Override public void run() { final Socket socket; try { socket = IO.socket("http://<IPv4 Address>:<port>"); socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { @Override public void call(Object... args) { Log.d("TAG", "Socket Connected!"); socket.disconnect(); } }); } catch(Exception e){ Log.e("Error", e.toString()); } } } 格式下有一个动态表格,其格式不同,我不知道如何将这些行转换为列。有人可以帮忙吗?

ColumnName

目标国家

ColumnName      ColumnValue
AccountNumber   123456
AccountBalance  250
AccountState    TX
AccountCity     Houston

1 个答案:

答案 0 :(得分:1)

您可以使用dynamic crosstab

CREATE TABLE tbl(
    ColumnName  VARCHAR(20),
    ColumnValue VARCHAR(20)
);
INSERT INTO tbl VALUES
('AccountNumber', '123456'),
('AccountBalance', '250'),
('AccountState', 'TX'),
('AccountCity', 'Houston');

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql =
'SELECT' + CHAR(10);

SELECT @sql = @sql + 
'   MAX(CASE WHEN ColumnName = ' +QUOTENAME(ColumnName, '''') + ' THEN ColumnValue END) AS ' + QUOTENAME(ColumnName) + ',' + CHAR(10)
FROM tbl;
SELECT @sql = SUBSTRING(@sql, 0, LEN(@sql) - 1);

SELECT @sql = @sql + CHAR(10)
+ 'FROM tbl'

PRINT @sql;
EXEC(@sql);

DROP TABLE tbl;

ONLINE DEMO