在SQL Server中将宽转换为长结构而无需在两列上进行聚合

时间:2018-09-18 15:12:20

标签: sql sql-server

我有一个看起来像这样的表:

zip      y       z
---------------------
99555   1.1      1.1
99556   1.1      0.8

我正在尝试通过给y命名为Const来将输出转换为长结构。和z为NonConst的别名。

zip      Value          Type
---------------------------------
99555     1.1           Const.
99555     1.1           NonConst.
99556     1.1           Const.
99556     .8            NonConst.

我尝试了case when end条语句,但是没有用。还有其他方法吗?我正在使用SQL Server。

解决方案:

CREATE table #yourtable
(
     [zip] int,  
     [y] float, 
     [z] float
)

INSERT INTO #yourtable ([zip], [y], [z])
VALUES (99555, 1.1, 1.1),
       (99556, 1.1, .8)

SELECT 
    t.zip, tt.value, tt.z
FROM
    #yourtable t 
CROSS APPLY
    (VALUES ('Const.', y), ('NonConst.', z)) tt(Value, z);

1 个答案:

答案 0 :(得分:1)

我建议apply

select t.zip, tt.value, tt.z as Type
from table t cross apply
     ( values ('Const.', y), ('NonConst.', z) 
     ) tt(Value, z);