两个日期/期间在同一个select语句中,并返回每个期间的数据

时间:2017-03-06 19:36:00

标签: sql sql-server tsql

好的,我有一段代码可以获取与美元视图相关的数据,包括位置,操作,异常和最终消费。这是由FYPeriod完成的。让我们说这返回了FYPeriod 11702,即2016年8月。我也希望它返回同一行FYPeriod 11602,即2015年8月。我尝试添加另一个连接并简单地做一个(FYPeriod - 100),但当然这没有返回任何内容。以下是返回FYPeriod的工作代码。

SELECT dbo.fiscalmonthyearstring(f.FYPeriod) As MonthYear, f.FYPeriod, c.SYSTEMPLANT, e.SpendingAcct, 
c.DOLLARS, f.Data AS Units, d.exceptions, f.PLActivity
    FROM [vw_TotalDollars] c 
    LEFT JOIN [dbo].[location] b ON b.PlantId = c.SYSTEMPLANT
    LEFT JOIN [Operations] f ON f.FYPeriod = c.PST 
AND f.location = b.location
    JOIN [dbo].[aexceptions] d ON b.PlantId = d.Id
AND d.acc = c.ACCN
AND exceptions IN ('Z2', 'X2'  , 'Z7' , 'X7')
    LEFT JOIN [dbo].[Spending] e ON e.SpendingId = d.SpendingId
    WHERE f.PLActivity = 'Total Produced'

我希望我已经正确解释了这一点,如果没有,我会尝试这样做。

Current output

1 个答案:

答案 0 :(得分:0)

假设您需要进行所有过滤以获取上一年的数据,我们可以将您当前的查询包装在common table expression中,以便我们可以自行引用它:

;with cte as (
  select 
      o.fyperiod
    , td.systemplant
    , s.SpendingAcct
    , td.dollars
    , o.[Data] as Units
    , ae.exceptions
    , o.plactivity
  from [vw_TotalDollars] td
    inner join [Operations] o
      on o.fyperiod   = td.pst 
     and o.plactivity = 'Total Produced'
    left join [dbo].[location] l
      on l.PlantId  = td.systemplant
     and l.location = o.location
    left join [dbo].[aexceptions] ae
      on ae.Id  = td.systemplant
     and ae.acc = td.accn
     and ae.exceptions in ('Z2','X2','Z7','X7')
    left join [dbo].[Spending] s
      on s.SpendingId = ae.SpendingId
)
select
    cte.FyPeriod
  --, MonthYear = dbo.fiscalmonthyearstring(cte.fyperiod)
  , cte.SystemPlan
  , cte.SpendingAcct
  , cte.Dollars
  , cte.Units
  , cte.Exceptions
  , cte.Plactivity
  --, pyMonthYear = dbo.fiscalmonthyearstring(py.fyperiod)
  , pyDollars   = py.Dollars
  , pyUnits     = py.Units
from cte
  left join cte as py 
    on py.fyperiod     = cte.fyperiod-100
   and py.systemplant  = cte.systemplant
   and py.exceptions   = cte.exceptions
   and py.SpendingAcct = cte.SpendingAcct

注意:如果重写为内联表值函数,则标量函数dbo.fiscalmonthyearstring()的性能会更好。

内联表值函数与标量函数参考: