0

任何人都可以协助我尝试编写一个 sql 语句吗?我正在使用 SSRS r1(sql 或 ssrs 解决方案都可以)

我如何能:

  • 显示按月和年拆分的计数度量
  • 对于每个月,我想计算上一个累计 12 个月

例如

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

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

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)
4

1 回答 1

0

在这里,您对查询有一个想法,它必须如下所示;

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
于 2013-01-22T21:45:25.097 回答