• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
张继东
看铁蹄铮铮,踏遍万里河山。磨不破,打不烂。
   首页    新随笔    联系   管理    订阅  订阅

朋友问的一个关于group by的sql

提问:
         一个表有三个字段id,dt,d  分别存放id,时间,数值 
id    dt    d
1 2004-08-11 12:12:00.000 9 
2 2005-09-11 12:08:00.000 2 
3 2005-08-11 12:12:00.000 6 
4 2005-09-11 12:12:00.000 10 
5 2005-08-11 12:12:00.000 0 
要求按照时间里的月份分组求d字段和
回答:
    相应sql如下:

 1if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[abc]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
 2drop table [dbo].[abc] 
 3GO 
 4 
 5CREATE TABLE [dbo].[abc] ( 
 6    [id] [int] NOT NULL , 
 7    [dt] [datetime] NULL , 
 8    [d] [int] NULL  
 9) ON [PRIMARY] 
10GO 
11 
12 
13insert into abc (id,dt,d) values(1,'2004-08-11 12:12:00',9) 
14insert into abc (id,dt,d) values(2,'2005-09-11 12:8:00',2) 
15insert into abc (id,dt,d) values(3,'2005-08-11 12:12:00',6) 
16insert into abc (id,dt,d) values(4,'2005-09-11 12:12:00',10) 
17insert into abc (id,dt,d) values(5,'2005-08-11 12:12:00',0) 
18insert into abc (id,dt,d) values(6,'2004-11-2 12:12:00',4)
19insert into abc (id,dt,d) values(7,'2004-11-10 12:12:00',4)
20insert into abc (id,dt,d) values(8,'2004-11-30 12:12:00',4)
21 
22select * from abc 
23select datepart(month,dt)as 月份,sum(d) as 合计  from abc group by datepart(month,dt) 
24
25

其实就用了一个DATEPART函数
引申一下:如果统计1,2,3,4,5,6,7,8,9,10,11月上旬,11月中下旬,12月的怎么办?
可以这样:
1 select case datepart(month,dt)
2 when 11 then case sign(datepart(day,dt)-11) when -1 then 11 else 13 end
3 else datepart(month,dt) end as 月份,
4 sum(d) as 统计 
5 from abc group by 
6 case datepart(month,dt)
7 when 11 then case sign(datepart(day,dt)-11) when -1 then 11 else 13 end
8 else datepart(month,dt) end
再引申,如果统计把年月作为分组统计的依据可以这样:
select datename(year,dt)+datename(month,dt)as 年月 ,sum(d) as 统计 from abc group by datename(year,dt)+datename(month,dt)
最后,明白group by 后面不仅可以跟字段名就可以了。
------------------------------------------------------------------
再问再续:
1 按照旬统计
1 select 
2case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end as 旬,
3 sum(d) as 统计 
4 from abc group by 
5case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end 

2按 年+旬 分组统计
 select
datename(year,dt)+datename(month,dt)+case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end as 日期, sum(d) as 统计
 from abc group by
 datename(year,dt)+datename(month,dt)+case (datepart(day,dt)-1)/10 when 0 then '上旬' when 1 then '中旬' else '下旬' end

posted @ 2005-09-01 12:05  简单生活  阅读(1436)  评论(9)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3