我真的很难处理查询。我想要在2014年8月到2015年7月之间的每个月的总和。如果我在where子句中指定日期之间它将所有月份相加。
这是我的问题:
DECLARE @CurrentYear int = DATEpart(year,getdate())
DECLARE @PreviousYear int = DATEpart(year,getdate()) -1
SELECT
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'08') THEN a.balance ELSE 0 END) AS BalanceAug ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'09') THEN a.balance ELSE 0 END) AS BalanceSep ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'10') THEN a.balance ELSE 0 END) AS BalanceOct ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'11') THEN a.balance ELSE 0 END) AS BalanceNov ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'12') THEN a.balance ELSE 0 END) AS BalanceDec ,
...etc.
FROM subaccount_history a with (nolock)
WHERE fin_period between concat(@PreviousYear,'08') and concat(@CurrentYear,'12')
问题在于inter子句,我尝试过group by,但是也没有用。它将指定的两个日期之间的所有内容相加。