0

我有一张像

att1 att2 att3 att4
-------------------
1    6    11    16
2    7    12    17 
3    8    13    18
4    9    14    19 

将表格作为坐标系的查询是什么:

a b val
-------
1 1  1
1 2  6 
1 3  11
1 4  16
2 1  2
2 2  7 
2 3  12
2 4  17
3 1  3
3 2  8
3 3  13
3 4  18
4 1  4
4 2  9
4 3  14
4 4  19

目前我有:

select 1,att1 from data_journal_insurance_raw union all
select 2,att2 from data_journal_insurance_raw union all
select 3,att3 from data_journal_insurance_raw union all
select 4,att4 from data_journal_insurance_raw

我错过了'b'部分怎么办?

4

2 回答 2

1

如果我理解正确,您希望将表格转换为包含行、列和值的表格。

实际上,你错过了这个a部分。a代表行和b列。以下查询应该对您有所帮助。

WITH cte AS (SELECT ROW_NUMBER() OVER (ORDER BY att1) AS a, * FROM data_journal_insurance_raw)
SELECT a, 1 as b, CAST(att1 AS VARCHAR(MAX)) FROM cte UNION ALL
SELECT a, 2 as b, CAST(att2 AS VARCHAR(MAX)) FROM cte UNION ALL
SELECT a, 3 as b, CAST(att3 AS VARCHAR(MAX)) FROM cte UNION ALL
SELECT a, 4 as b, CAST(att4 AS VARCHAR(MAX)) FROM cte
ORDER BY a, b

请注意,我将 value 列转换为VARCHAR(MAX),因为我不知道您的表中有哪些数据类型。如果它们都是数字,那么您可以删除这些CAST函数。

如果你只在一张桌子上这样做一次,那么这对你来说很好。但是,如果您希望能够在各种表上执行此操作,您可以让 SQL Server 为您编写代码。这是一个可以做到这一点的程序:

CREATE PROCEDURE usp_Coordinate_table(@TableName NVARCHAR(200)) AS
BEGIN
    DECLARE @sql NVARCHAR(MAX);
    WITH cte AS (SELECT TOP 1 c.name FROM sys.columns c, sys.objects o WHERE c.object_id = o.object_id AND o.name = @TableName)
    SELECT @sql = 'WITH RowData AS (SELECT ROW_NUMBER() OVER (ORDER BY '+name+') AS RowNum, * FROM '+@TableName+') ' FROM cte;

    WITH ColData AS (SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS ColNum, c.name 
        FROM sys.columns c, sys.objects o WHERE c.object_id = o.object_id AND o.name = @TableName)
    SELECT @sql = @sql + 'SELECT RowNum, '+CAST(c.ColNum AS VARCHAR)+' AS ColNum, CAST('+c.name+' AS VARCHAR(MAX)) AS Value FROM RowData UNION ALL '
    FROM ColData c

    SET @sql = SUBSTRING(@sql, 1, LEN(@sql) - 10) + ' ORDER BY RowNum, ColNum'
    EXEC sp_executesql @sql
END
于 2012-05-03T11:13:56.047 回答
0

您应该在 Union 中有 3 列

select att1 ,1,att1 from data_journal_insurance_raw union
select att1 ,2,att2 from data_journal_insurance_raw union
select att1 ,3,att3 from data_journal_insurance_raw union
select att1 ,4,att4 from data_journal_insurance_raw
于 2012-05-03T06:52:03.160 回答