请教sql分组后取每组最小值的问题。

ky4008sh 2012-08-30 10:00:11
[color=#808080]表名:Game

P_Time P_Kaisu
2012-12-12 14:05:20 1
2012-12-12 15:55:50 4
2012-12-12 15:06:11 8
2012-12-12 12:05:12 5
2012-12-13 13:07:22 14
2012-12-13 15:08:21 21
2012-12-13 15:09:11 11
2012-12-13 15:11:22 22
2012-12-14 15:12:27 27
2012-12-14 15:14:25 25
2012-12-14 15:15:32 32
2012-12-14 15:16:35 35

想得到以下结果: 每一天(只显示日期)的最小值
P_Time P_Kaisu
2012-12-12 1
2012-12-13 11
2012-12-14 25








...全文
786 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jack_3166 2012-08-30
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]
谢谢大家,问题解决了。
以下两位的已证实,谢谢

ssp2009:
select convert(varchar(10),P_Time,120),min(P_Kaisu)
from Game group by convert(varchar(10),P_Time,120)

筱筱澄:
select convert(nchar(10),P_Time,120 ) as ……
[/Quote]

convert(varchar(10),P_Time,120)这个是将你的时间日期型转换为10位长度的字符串。
然后根据这个字符串去分组,
min()函数是取每个分组里面P_Time的最小值,Max()函数是取最大值
Jack_3166 2012-08-30
  • 打赏
  • 举报
回复
没看,被人抢先了。。。
Jack_3166 2012-08-30
  • 打赏
  • 举报
回复
create table #tb(P_Time datetime,P_Kaisu int)

insert into #tb
select N'2012-12-12 14:05:20',1 union all
select N'2012-12-12 15:55:50', 4 union all
select N'2012-12-12 15:06:11', 8 union all
select N'2012-12-12 12:05:12', 5 union all
select N'2012-12-13 13:07:22', 14 union all
select N'2012-12-13 15:08:21', 21 union all
select N'2012-12-13 15:09:11', 11 union all
select N'2012-12-13 15:11:22', 22 union all
select N'2012-12-14 15:12:27', 27 union all
select N'2012-12-14 15:14:25', 25 union all
select N'2012-12-14 15:15:32', 32 union all
select N'2012-12-14 15:16:35', 35


select convert(varchar(10),P_Time,121)as P_Time,min(P_Kaisu) as P_Kaisu
from #tb
group by convert(varchar(10),P_Time,121)
以学习为目的 2012-08-30
  • 打赏
  • 举报
回复


select convert(carhcar(10),P_Time,120 ) as P_Time,min(P_Kaisu)
from tb
group by convert(carhcar(10),P_Time,120 )

--下面这个也可以的,就是一个判断、子查询
select *
from tb t
where not exists (select 1 from tb where datediff(dd,t.p_time,p_time)=0 and p_kaisu < t.p_kaisu)
ky4008sh 2012-08-30
  • 打赏
  • 举报
回复
谢谢大家,问题解决了。
以下两位的已证实,谢谢

ssp2009:
select convert(varchar(10),P_Time,120),min(P_Kaisu)
from Game group by convert(varchar(10),P_Time,120)

筱筱澄:
select convert(nchar(10),P_Time,120 ) as P_Time,min(P_Kaisu)
from Game
group by convert(nchar(10),P_Time,120 )

AcHerat: 刚学sql语句,看不太懂,还是谢谢你.




  • 打赏
  • 举报
回复

select convert(varchar(10),P_Time,120) P_Time,min(P_Kaisu) P_Kaisu
from Game
group by convert(varchar,P_Time,120) P_Time
快溜 2012-08-30
  • 打赏
  • 举报
回复
select convert(varchar(10),P_Time,120),min(P_Kaisu)
from tb group by convert(varchar(10),P_Time,120)
筱筱澄 2012-08-30
  • 打赏
  • 举报
回复
select convert(carhcar(10),P_Time,120 ) as P_Time,min(P_Kaisu)
from tb
group by convert(carhcar(10),P_Time,120 )
AcHerat 2012-08-30
  • 打赏
  • 举报
回复

select *
from tb t
where not exists (select 1 from tb where datediff(dd,t.p_time,p_time)=0 and p_kaisu < t.p_kaisu)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧