首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

一个按要求合并行的有关问题

2012-01-12 
一个按要求合并行的问题表单编号接收时间审批步骤是否终止10012006-12-111否10012006-12-112否10012006-12

一个按要求合并行的问题
表单编号       接收时间             审批步骤       是否终止
1001             2006-12-11                 1                     否
1001             2006-12-11                 2                     否
1001             2006-12-12                 3                     是
1002             2006-12-09                 1                     否
1002             2006-12-11                 2                     否

我只想知道某编号的总体情况而已:
表单编号       发起时间           是否终止
1001             2006-12-11                 是                    
1002             2006-12-09                 否
发起时间是第一步的接收时间,是否终止是看当前最后一步的是否终止

另外,请问哪本书有讲这方面知识的?谢谢

[解决办法]
--测试数据
create table 表(表单编号 int,接收时间 datetime,审批步骤 int,是否终止 varchar(2))
insert 表 select 1001, '2006-12-11 ', 1, '否 '
union select 1001, '2006-12-11 ', 2, '否 '
union select 1001, '2006-12-12 ', 3, '是 '
union select 1002, '2006-12-09 ', 1, '否 '
union select 1002, '2006-12-11 ', 2, '否 '
go


select 表单编号,发起时间=min(接收时间),
是否终止=(select 是否终止 from 表 b
where b.表单编号=a.表单编号
and not exists(select 1 from 表 where 表单编号=b.表单编号 and 接收时间> b.接收时间))
from 表 a
group by 表单编号

--删除测试数据
drop table 表

/*结果

表单编号 发起时间 是否终止
----------- ------------------------------------------------------ ----
1001 2006-12-11 00:00:00.000 是
1002 2006-12-09 00:00:00.000 否

*/
[解决办法]
create table T(表单编号 char(4), 接收时间 datetime, 审批步骤 int, 是否终止 nvarchar(1))
insert T select '1001 ', '2006-12-11 ', 1, '否 '
union all select '1001 ', '2006-12-11 ', 2, '否 '
union all select '1001 ', '2006-12-12 ', 3, '是 '
union all select '1002 ', '2006-12-09 ', 1, '否 '
union all select '1002 ', '2006-12-11 ', 2, '否 '

select 表单编号,
发起时间=(select 接收时间 from T where 审批步骤=1 and 表单编号=A.表单编号),
是否终止=(select 是否终止 from T where 表单编号=A.表单编号 and 审批步骤=max(A.审批步骤))
from T as A
group by 表单编号

--result
表单编号 发起时间 是否终止
---- ------------------------------------------------------ ----
1001 2006-12-11 00:00:00.000 是


1002 2006-12-09 00:00:00.000 否

(2 row(s) affected)

[解决办法]
select 表单编号,
发起时间=(select 接收时间 from T where 审批步骤=1 and 表单编号=A.表单编号),
是否终止=(select 是否终止 from T where 表单编号=A.表单编号 and 审批步骤=max(A.审批步骤))
from T as A
group by 表单编号


[解决办法]
select *
into #ls
from (
select '1001 'as '表单编号 ', '2006-12-11 ' as '接收时间 ', '1 'as '审批步骤 ', '否 'as '是否终止 '
union all select '1001 ', '2006-12-11 ', '2 ', '否 '
union all select '1001 ', '2006-12-12 ', '3 ', '是 '
union all select '1002 ', '2006-12-09 ', '1 ', '否 '
union all select '1002 ', '2006-12-11 ', '2 ', '否 ') t
/*************核心语句*************/
select a.表单编号,接收时间,a.审批步骤,是否终止 from #ls a
join
(select 表单编号,count(*) as 审批步骤 from #ls group by 表单编号) b
on a.表单编号=b.表单编号 and a.审批步骤=b.审批步骤
/*************核心语句*************/
drop table #ls
[解决办法]
select 编号,min(接收时间),是否终止=(select 是否终止 from table where 接收时间 <a.接收时间 and 编号=a.编号) from table a group by 编号

热点排行