热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SQL累积前12个月-每月细分-SQLcumulativeprevious12months-breakdownpermonth

CananyoneassistinasqlstatementIamtryingtowrite?ImusingSSRSr1(eithersqlorssrssol

Can anyone assist in a sql statement I am trying to write? I'm using SSRS r1 (either sql or ssrs solution is fine)

任何人都可以协助我试图编写的sql语句吗?我正在使用SSRS r1(无论是sql还是ssrs解决方案都很好)

How do I:

我如何能:

  • show count measure split by month and year
  • 显示按月和年分的计数

  • for each of those months, I want to count the previous cumulative 12 months
  • 对于这几个月中的每一个月,我想要计算之前累计的12个月

e.g.

2012 jan: counts feb 2011 - jan 2012
2012 feb: counts mar 2011 - feb 2012
2012 mar: counts apr 2011 - mar 2012

I have started this code but it's incorrect, however it gives you an idea of what I am trying to achieve (this issue is I have to calc month and year from a date)

我已经启动了这段代码,但它不正确,但是它让你知道我想要实现的目标(这个问题是我必须从一个日期开始计算月份和年份)

select 
    count(a.measure) count
    ,month(a.StartDate)
    ,year(a.StartDate)
from
    a
where 
    a.StartDate >=  DATEADD(mm,DATEDIFF(mm,0,@datepromt)-12,0) as startdateYrAgo --1st month 1 year ago 01/01/2012 
    and a.StartDate <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@datepromt)+1,0)) as startdateEOM --last day of month 31/01/2013
group by 
    month(a.StartDate)
    ,year(a.StartDate)

1 个解决方案

#1


0  

Here you have an idea for the query, it have to look something like below;

在这里你有一个查询的想法,它必须看起来像下面;

SELECT 
 periods.year
,periods.month
,measures.cnt
FROM (
    SELECT DISTINCT
      year = YEAR(StartDate)
    , mOnth= MONTH(StartDate)
    , month_running = DATEDIFF(mm, 0, StartDate) 
    FROM a
    GROUP BY YEAR(StartDate), MONTH(StartDate), DATEDIFF(mm, 0, StartDate) 
) periods
JOIN (
    SELECT month_running = DATEDIFF(mm, 0, StartDate), cnt = COUNT(measure) 
    FROM a
    GROUP BY DATEDIFF(mm, 0, StartDate) 
) measures
ON measures.month_running BETWEEN periods.month_running - 12 AND periods.month_running - 1

推荐阅读
author-avatar
迷蒙的天蝎
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有