在按期间

时间:2015-11-14 15:03:18

标签: sql sql-server-2005 group-by case

我正在尝试使用以下代码来计算期间和工厂的过去12个月内所有行的计数,请参阅下面的输出。 因此,例如使用以下输出,而不是当前包含该期间总计的12个月列,我希望计数使用201001-201101之间的时间段(请注意,我的示例仅针对下面的数据集和12个月列需要适应每个时期。)

Period    Plant Stock   Special MonthTotal  12Months
201101    0EA0    27     0          27        27
201101    0EB0    35    2           37        37

我遇到的问题是,我的代码只是带来了当前时期的计数,而不是过去12个月的计算。请有人帮忙吗?

   select 
            convert(varchar(6),dateadd(mm,0,P.Dt),112) as Period,P.Plant,
            Sum(Case When Left(Upper(Material),2) = 'ZZ' then 1 else 0 end) as Stock,
            Sum(Case When Left(Upper(Material),2) <> 'ZZ' then 1 else 0 end) as Special
            ,Count(*) as MonthTotal,Sum(Case When 
                        convert(varchar(6),dateadd(mm,0,P.Dt),112)  
                 Between
                        convert(varchar(6),dateadd(mm,-12,P.Dt),112)    
                 And
                        convert(varchar(6),dateadd(mm,0,P.Dt),112)  Then 1 else 0 End
                )as [12Months]
    from 
            iesaonline.dbo.DS_POs  as P where  
                                Plant IN(
                    Select Client From METRICS.DBO.CO_001_Plants_090_Final
                                  where CustGrp = 'Hovis'
                                        )
    Group by 
            P.Plant,convert(varchar(6),dateadd(mm,0,P.Dt),112)                                  
    order by 
            convert(varchar(6),dateadd(mm,0,Dt),112),Plant      

2 个答案:

答案 0 :(得分:3)

问题似乎是你按年/月进行分组,并试图将年/月范围之外的值加起来。没有样本数据,我无法确定,但听起来你想要滚动12个月的总和。像下面这样的东西可以让你到达你想去的地方。

<IncludeRetElement>Desc</IncludeRetElement>

答案 1 :(得分:3)

没有必要同时做所有事情。

首先获得月度值更容易

SELECT DATEADD(month, DATEDIFF(month, 0, Dt), 0) as FOM
     , Plant
     , Stock = SUM(CASE WHEN LEFT(Upper(Material), 2) = 'ZZ' THEN 1 ELSE 0 END)
     , Special = SUM(CASE WHEN LEFT(Upper(Material), 2) = 'ZZ' THEN 0 ELSE 1 END)
FROM   DS_POs
GROUP BY Plant, DATEADD(month, DATEDIFF(month, 0, Dt), 0)

并使用该作为基础,使用CROSS APPLY

获取过去12个月的结果
WITH DS_POSM AS (
    SELECT DATEADD(month, DATEDIFF(month, 0, Dt), 0) as FOM
         , Plant
         , Stock = SUM(CASE WHEN LEFT(Upper(Material), 2) = 'ZZ' THEN 1 ELSE 0 END)
         , Special = SUM(CASE WHEN LEFT(Upper(Material), 2) = 'ZZ' THEN 0 ELSE 1 END)
    FROM   DS_POs
    GROUP BY Plant, DATEADD(month, DATEDIFF(month, 0, Dt), 0)
)
SELECT Convert(char(6), FOM, 112) Period
     , Plant
     , Stock
     , Special
     , MonthTotal = Stock + Special
     , ly.[12Months]
FROM   DS_POSM a
       CROSS APPLY (SELECT Sum(Stock + Special) [12Months]
                    FROM   DS_POSM lastyear 
                    WHERE  lastyear.FOM Between DateAdd(mm, -12, a.FOM) And a.FOM
                      AND  lastyear.Plant = a.Plant
                   ) ly
ORDER BY FOM, Plant

DATEADD(month, DATEDIFF(month, 0, Dt), 0)获取Dt

月份的第一天