第1个回答 2011-07-15
select * from(select id,max(cast(riqi+' '+shijian as datetime)) as newt from kq group by id,riqi
union all
select id,min(cast(riqi+' '+shijian as datetime))as newt from kq group by id,riqi)a
order by a.id ,a.newt
--插入测试数据:
create table kq
(
id varchar(3),
riqi varchar(10),
shijian varchar(8)
)
go
insert into kq
select '001' ,'2011-4-1','07:55:00'union all
select '001' ,'2011-4-1','12:02:00'union all
select '001' ,'2011-4-1','12:26:00'union all
select '001' ,'2011-4-1','18:56:00'union all
select '001' ,'2011-4-2','07:55:00'union all
select '001' ,'2011-4-2','12:02:00'union all
select '001' ,'2011-4-2','12:26:00'union all
select '001' ,'2011-4-2','18:56:00'union all
select '002' ,'2011-4-1','07:55:00'union all
select '002' ,'2011-4-1','12:02:00'union all
select '002' ,'2011-4-1','12:26:00'union all
select '002' ,'2011-4-1','18:56:00'union all
select '002' ,'2011-4-2','07:55:00'union all
select '002' ,'2011-4-2','12:02:00'union all
select '002' ,'2011-4-2','12:26:00'union all
select '002' ,'2011-4-2','18:56:00'
go
执行测试结果:
id newt
---- ------------------------------------------------------
001 2011-04-01 07:55:00.000
001 2011-04-01 18:56:00.000
001 2011-04-02 07:55:00.000
001 2011-04-02 18:56:00.000
002 2011-04-01 07:55:00.000
002 2011-04-01 18:56:00.000
002 2011-04-02 07:55:00.000
002 2011-04-02 18:56:00.000
(所影响的行数为 8 行)
第2个回答 2011-07-15
用where设置两个区间就行了,我写日期格式可能不对,你自己调一下
select id,riqi,shijian from kq where kq.shijian>date(18:00:00) or kq.shijian<date(09:30:00)
第3个回答 2011-07-15
select id,riqi,min(shijian),max(shijian) from kq k group by id ,riqi
你如果不要中午的,可以再加个查询条件
select id,riqi,min(shijian),max(shijian) from kq where riqi>'....' or riqi<'....' k group by id
第4个回答 2011-07-16
如果你的表中存在唯一编号最好了。如果没有,则你可以为该表增加一个字段叫aid 要求自增,且为主键。
那么下面就可以开始选择id 相同的第一条记录了。
比如表名叫tmpTable,则有:
第一种解决方式:
你可以选择用分组函数,也就是group by,那么id之外的所有列,你就要对他们使用聚合函数,比如max最大值,min最小值,count计算行数等,语句的例子:
select id,max(任意列),min(任意列),count(任意列)
from table
注:这里可以增加个where条件,用来筛选你的数据
group by id
第二种:
就是根据某一列来排序,用row_number()来筛选数据,例如
select aa.*
from
(select a.*,
row_number() over(partition by a.id order by 你需要排序的列) n1
from table a )aa
where aa.n1=1