sql server 时间按照月、周分组

liangfeilonglfl 2011-06-20 11:20:54
表有个dateTime字段,需要根据年按照月份分组,根据月份按照周进行分组!请问实现这个功能的sql语句是什么呢?
...全文
638 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
X_0 2011-06-20
  • 打赏
  • 举报
回复

select smonth=month(dt),......
from tb
where year(dt)=2011
group by month(dt)

--根據周分組 group by datepart(wk,dt)
wujianfeng32 2011-06-20
  • 打赏
  • 举报
回复
order by year(),month(),datepart(week, ) O(∩_∩)O~
Lyongt 2011-06-20
  • 打赏
  • 举报
回复

1. 根据年按照月份分组
Select MONTH(dt) as 月份, SUM(数量)
Where Year(dt) = '2011'
Group By Month(dt)

2.根据月份按照周进行分组
Select datepart(Weekd, dt) as 周, SUM(数量)
Where Month(dt) = 6
Group By datepart(Weekd, dt)
xuexiaodong2009 2011-06-20
  • 打赏
  • 举报
回复
3分组取每组的前N个数据

开发中还会遇到需要对某一组数据先分组,然后取每组的前n条记录的情况

不妨试试如下代码

/*

按CurrentNodeLevel列分组,每组按NodeID排序,取出每个组中的前3个元素
*/
declare @temp table (NodeID int, CurrentNodeLevel int ,rowNumber int)--定义临时表
insert into @temp
select NodeID,CurrentNodeLevel,ROW_NUMBER()
OVER ( partition by CurrentNodeLevel
order by NodeID ) as rowNumber
from SchoolTerminalStruct---给临时表中插入数据
select * from @temp where rowNumber<=3--从临时表中取数据
http://user.qzone.qq.com/270769564/infocenter
--小F-- 2011-06-20
  • 打赏
  • 举报
回复
group by month(时间字段)
group by datepart(wk,时间字段)

22,206

社区成员

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

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