你说的这一行呀,实际上就是要ID和日期都相同的记录合并成新的记录!上面那些只是模拟数据表的一部分!ID等于1的我列了二一的记录吗!ID等于的还可以列很多吗!
解决方案 »
- group by用法
- sql server 2008里怎样做数据定时自动备份功能
- 如何获取日期部分
- 关于group by问题,需要按时间的某天来分组sum(),但是在group by后面使用Convert(varchar(10),time,120)会报‘time不在聚合函数与group by子句的错误!
- 我一个数据库的所有数据表都无法打开浏览了?
- ※※※数据合并※※※
- 请教各位大虾如何查出一个表中有unicode制约的字段?
- 急急,触发器失败后怎么不影响插入数据?
- 单机版数据库在向sql server 7升级过程中,遇到问题,请指教!
- ms sql server内存问题
- 存储过程问题,请高手进来看看。-----在线等待解答
- 安装sql server2000时有一个问题,一直困扰着我,请熟悉的朋友给我解释一下。
select id,[DateTime]
,Time1=max(case gid%4 when 0 then [Time] else '' end)
,Time2=max(case gid%4 when 1 then [Time] else '' end)
,Time3=max(case gid%4 when 2 then [Time] else '' end)
,Time4=max(case gid%4 when 3 then [Time] else '' end)
from(
select id,[DateTime]=convert(char(10),[DateTime],120)
,[Time]=convert(char(10),[DateTime],108)
,gid=(select count(*) from tb where id=a.id and [DateTime]<=a.[DateTime])-1
from tb a
)a group by id,[DateTime],gid/4
create table tb(ID int,[DateTime] datetime)
insert tb select 1,'2004-1-1 08:30:00'
union all select 1,'2004-1-1 12:00:00'
union all select 1,'2004-1-1 13:30:00'
union all select 1,'2004-1-1 17:30:00'
union all select 1,'2004-1-2 08:30:00'
union all select 1,'2004-1-2 12:00:00'
union all select 1,'2004-1-2 13:30:00'
union all select 1,'2004-1-2 17:30:00'
union all select 2,'2004-1-1 08:30:00'
union all select 2,'2004-1-1 12:00:00'
union all select 2,'2004-1-1 13:30:00'
union all select 2,'2004-1-1 17:30:00'
go--查询(如果 ID + [DateTime] 不会重复的话)
select id,[DateTime]
,Time1=max(case gid%4 when 0 then [Time] else '' end)
,Time2=max(case gid%4 when 1 then [Time] else '' end)
,Time3=max(case gid%4 when 2 then [Time] else '' end)
,Time4=max(case gid%4 when 3 then [Time] else '' end)
from(
select id,[DateTime]=convert(char(10),[DateTime],120)
,[Time]=convert(char(10),[DateTime],108)
,gid=(select count(*) from tb where id=a.id and [DateTime]<=a.[DateTime])-1
from tb a
)a group by id,[DateTime],gid/4
go--删除测试
drop table tb/*--测试结果id DateTime Time1 Time2 Time3 Time4
----------- ---------- ---------- ---------- ---------- ----------
1 2004-01-01 08:30:00 12:00:00 13:30:00 17:30:00
1 2004-01-02 08:30:00 12:00:00 13:30:00 17:30:00
2 2004-01-01 08:30:00 12:00:00 13:30:00 17:30:00 (所影响的行数为 3 行)
--*/
,convert(varchar(10),DateTime,102)
,Time1=max(case when datepart(hh,DateTime)=8
then convert(varchar(10),DateTime,108) else '' end)
,Time2=max(case when datepart(hh,DateTime)=12
then convert(varchar(10),DateTime,108) else '' end)
,Time3=max(case when datepart(hh,DateTime)=13
then convert(varchar(10),DateTime,108) else '' end)
,Time4=max(case when datepart(hh,DateTime)=17
then convert(varchar(10),DateTime,108) else '' end)
from @tb
group by ID,convert(varchar(10),DateTime,102)