创建不同的列值作为额外的行

时间:2011-10-11 23:07:14

标签: sql sql-server

任何人都可以分享如何操纵下表的任何技巧

ID TYPE Name Description
1  X    A    DESC_A
2  X    B    DESC_B
3  Z    C    DESC_C

这个观点?

NAME_X DESCRIPTION_X
A      DESC_A
B      DESC_B
NAME_Z DESCRIPTION_Z
C      DESC_C 

对于每个不同的列,我想为“TYPE”列中的每个不同值创建一个自定义行。在此示例中,通过将TYPE值附加到“NAME_”和“DESCRIPTION _”来创建自定义行。

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

create view vwTestDistinctData
as
    select [type], [Description]
    from testdistinctdata
    union all
    select 
        'NAME_' + [type] as [Type],
        'DESCRIPTION_' + [type] as [Description]
    from testdistinctdata
    group by [type]
go

答案 1 :(得分:0)

编辑:从视图中返回一些元数据:

alter view dbo.yourView
as
with c_Distinct([type])
as  (   select  distinct [Type]
        from    dbo.yourTable   
    )
select  [Sort] = 0,
        [Type],
        Name, 
        [Description] 
from    dbo.yourTable
union all
select  [Sort] = 1,
        [Type],
        'NAME_'+[Type],
        'DESCRIPTION_'+[Type]
from    c_Distinct  

然后在从视图中选择时执行排序:

select *
from yourView
order by [Type] asc, [Sort] desc