日期:2014-05-18  浏览次数:20516 次

大家看看这个SQL要怎么实现。
公告标题 公告内容 公告时间
测试1 测试1 2012-02-14 14:10:14.000
  测试4 测试4 2012-02-14 14:10:14.000
测试2 测试2 2012-02-15 14:10:29.000
测试3 测试3 2012-02-16 14:10:37.000

这里数据库里面的数据格式。
 要求这样显示

  时间1(比如2-14) 2-15 2-16
  标题1 标题2 标题3
  标题4

时间是动态的,但是显示的时候要把时间作为列来显示。sql2005或者2008中。

------解决方案--------------------
SQL code

create table sx5
(公告标题 varchar(5), 公告内容 varchar(5), 公告时间 datetime)

insert into sx5
select '测试1', '测试1', '2012-02-14 14:10:14.000' union all
select '测试4', '测试4', '2012-02-14 14:10:14.000' union all
select '测试2', '测试2', '2012-02-15 14:10:29.000' union all
select '测试3', '测试3', '2012-02-16 14:10:37.000'


declare @sql varchar(6000),@ds varchar(2000)

select @ds=stuff(
(select ','+ds from
(select distinct '['+convert(varchar,公告时间,23)+']' ds from sx5) y
for xml path('')),1,1,'')

select @sql='select '+@ds
+'from 
(select row_number() over(partition by convert(varchar,公告时间,23) order by 公告时间) rn, 
公告标题,convert(varchar,公告时间,23) d from sx5) t
pivot(max(t.公告标题) for t.d in('+@ds+')) x'

exec(@sql)

2012-02-14 2012-02-15 2012-02-16
---------- ---------- ----------
测试1        测试2        测试3
测试4        NULL       NULL

(2 row(s) affected)