当前位置: 代码迷 >> Sql Server >> 表记录转置为多查询结果
  详细解决方案

表记录转置为多查询结果

热度:55   发布时间:2016-04-27 12:12:47.0
求助:表记录转置为多查询结果
表结构如下:
表A:
name string 
date datetime
07:00 bool
08:00 bool
。。。


表数据:
name date 07:00 08:00 09:00 10:00 11:00 12:00
gm 2012-06-20 1 0 1 0 1 0
gm 2012-06-11 1 0 1 0 0 0


求教:
按照每个time时间的bool值,只取true,如何让查询结果转变成为:

name date time
gm 2012-06-20 07:00
gm 2012-06-20 09:00
gm 2012-06-20 11:00
gm 2012-06-11 07:00
gm 2012-06-11 09:00


这样做是否可行?请教大家。









------解决方案--------------------
SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([name] varchar(2),[date] datetime,[07:00] int,[08:00] int,[09:00] int,[10:00] int,[11:00] int,[12:00] int)goinsert [test]select 'gm','2012-06-20',1,0,1,0,1,0 union allselect 'gm','2012-06-11',1,0,1,0,0,0godeclare @s nvarchar(4000)select @s=isnull(@s+' union all ','')+'select [name],[date],[time]='+quotename(Name,'''')+',[value]='+quotename(Name)+' from test'from syscolumns where ID=object_id('test') and Name not in('name','date')order by Colidexec('select name,convert(varchar(10),date,120) as date,time from(select * from ([email protected]+')t  )m where value=1 order by [name],[date]')/*name    date    time--------------------------------------gm    2012-06-11    07:00gm    2012-06-11    09:00gm    2012-06-20    11:00gm    2012-06-20    09:00gm    2012-06-20    07:00*/
  相关解决方案