分组查询问题

nayc 2007-08-19 05:39:21
表结构
id :标识列
insutype:类型 [int]
value :值 小数类型
createtime:创建时间 DateTime

问题如下:查询 按月和类型分组统计总和
现在的要求:不是按自然月查询,例如 :2007-07-27到2007-08-26 (包括边界)算一个月 算8月份的值
例如
id insutype value createtime
1 2 1 2007-07-26

2 1 8 2007-07-27
3 2 2 2007-08-11
4 1 8 2007-08-22

5 2 9 2007-08-27
6 1 9 2007-09-1
7 2 10 2007-10-1

查询出来的结果应该是这样
类型 值(sum) 时间
1 1 2007-07

2 2 2007-08
1 16 2007-08

2 9 2007-09
1 9 2007-09

2 10 2007-10


----------------
请各位帮忙了,万分感谢




...全文
211 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
nayc 2007-08-19
  • 打赏
  • 举报
回复
借用LS的数据:)我也写了个,各位给看看 有没有什么问题:)
declare @t table(id int,insutype int,value int,createtime DateTime)
insert @t
select 1, 2, 1, '2007-07-26' union all
select 2, 1, 8, '2007-07-27' union all
select 3, 2, 2, '2007-08-11' union all
select 4, 1, 8, '2007-08-22' union all
select 5, 2, 9, '2007-08-27' union all
select 6, 1, 9, '2007-09-1' union all
select 7, 2, 10, '2007-10-1'


select id,insutype,[value] ,createtime into #t1
from @t

update #t1 set createtime=dateadd(day,5,createtime) where day(createtime)>26

select insutype,sum([value]),year(createtime),month(createtime) from #t1
group by insutype,year(createtime),month(createtime)
order by year(createtime),month(createtime)
drop table #t1
hellowork 2007-08-19
  • 打赏
  • 举报
回复
----创建测试数据
declare @t table(id int,insutype int,value int,createtime DateTime)
insert @t
select 1, 2, 1, '2007-07-26' union all
select 2, 1, 8, '2007-07-27' union all
select 3, 2, 2, '2007-08-11' union all
select 4, 1, 8, '2007-08-22' union all
select 5, 2, 9, '2007-08-27' union all
select 6, 1, 9, '2007-09-1' union all
select 7, 2, 10, '2007-10-1'

----查询
SELECT insutype as 类型,
值 = sum(value),
时间 =
case
when day(createtime) >= 27
then convert(varchar(7),dateadd(month,1,createtime),120)
else convert(varchar(7),createtime,120)
end
FROM @t GROUP BY insutype,
case
when day(createtime) >= 27
then convert(varchar(7),dateadd(month,1,createtime),120)
else convert(varchar(7),createtime,120)
end
ORDER BY 3,1 DESC

/*结果
类型 值(sum) 时间
类型 值 时间
----------- ----------- -------
2 1 2007-07
2 2 2007-08
1 16 2007-08
2 9 2007-09
1 9 2007-09
2 10 2007-10
*/

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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