SQL语句,取数据库中前五条数据,并且把5条数据转成行的形式显示出来
SQL语句怎么写啊?
[解决办法]
如果是说要把它们显示在一行中,则:
select createdate,sum(case when rn=1 then torquevalue else 0 end) as [1],sum(case when rn=2 then torquevalue else 0 end) as [2],sum(case when rn=3 then torquevalue else 0 end) as [3],sum(case when rn=4 then torquevalue else 0 end) as [4],sum(case when rn=5 then torquevalue else 0 end) as [5]from(select torquevalue,createdate,rn from(select row_number()over(partition by createdate order by (select 1))rn from tb)t where rn<=5)t1 group by createdate
[解决办法]
;with f as(select id=row_number()over(order by getdate()),* from tb)select distinct b *from f across apply (select top 5 * from f where create=a.create order by id)b
[解决办法]
create table buqingle(x int, y date)insert into buqingle select 151,'2011-09-15' union allselect 152,'2011-09-15' union allselect 153,'2011-09-15' union allselect 154,'2011-09-15' union allselect 155,'2011-09-15' union allselect 156,'2011-09-15' union allselect 157,'2011-09-15' union allselect 181,'2011-09-18' union allselect 182,'2011-09-18' union allselect 183,'2011-09-18' union allselect 184,'2011-09-18' union allselect 185,'2011-09-18' union allselect 201,'2011-09-20' union allselect 202,'2011-09-20' union allselect 203,'2011-09-20' union allselect 204,'2011-09-20' union allselect 205,'2011-09-20'with t2 as(select y,x,rnfrom(select row_number() over(partition by y order by getdate()) rn,x,y from buqingle) twhere t.rn<=5)select y '日期',[1] '第一个值',[2] '第二个值',[3] '第三个值',[4] '第四个值',[5] '第五个值'from t2pivot(sum(x) for rn IN ([1],[2],[3],[4],[5])) t3 日期 第一个值 第二个值 第三个值 第四个值 第五个值---------- ----------- ----------- ----------- ----------- -----------2011-09-15 151 152 153 154 1552011-09-18 181 182 183 184 1852011-09-20 201 202 203 204 205(3 row(s) affected)