我有一个当前硬编码的查询,但需要用局部变量(年和月)替换。此外,它需要使用变量迭代一段时间(从2010年1月到2012年3月)。
需要将每个结果集插入到表中,并且需要在列(Period)中插入相应月份的时间戳。
SELECT DISTINCT
b.AccountInfo2
,SUM(ISNULL(CASE WHEN EntryTypeNr=1520 THEN -Amount END,0)) SumTotal1
,SUM(ISNULL(CASE WHEN EntryTypeNr IN (1521,1522,1523) THEN -Amount END,0)) SumTotal2
,Description
FROM AccountEntry a
INNER JOIN AccountBalance b ON a.AccountId = b.AccountId
AND a.AccountSubTypeNr = b.AccountSubTypeNr
WHERE (YEAR(a.ValueDate) = YEAR(GETDATE()) **@Variable1**) AND
(MONTH(a.ValueDate) = MONTH(GETDATE()) **@Variable2**) AND
(a.EntryTypeNr IN (1520, 1521, 1522, 1523)) AND
AccountInfo2<>''
GROUP BY AccountInfo2,Description
应插入结果集的表格包含以下列:
答案 0 :(得分:2)
基本上,这个问题是关于产生月份的。您可以使用递归CTE(语法类似于SQL Server)
来执行此操作with dates as (
select cast('2010-01-01' as date) as month_start
union all
select dateadd(month, month_start, 1)
from dates
where month_start <= '2012-03-01'
)
SELECT month_start, dateadd(month, 1, month_start) as month_end,
b.AccountInfo2,
SUM(CASE WHEN EntryTypeNr =1520 THEN -Amount ELSE 0 END) as SumTotal1,
SUM(CASE WHEN EntryTypeNr IN (1521, 1522, 1523) THEN -Amount ELSE 0 END) as SumTotal2,
Description
FROM AccountEntry a INNER JOIN
AccountBalance b
ON a.AccountId = b.AccountId AND
a.AccountSubTypeNr = b.AccountSubTypeNr join
dates
on YEAR(a.ValueDate) = YEAR(dates.month_start) AND
MONTH(a.ValueDate) = MONTH(dates.month_start)
WHERE (a.EntryTypeNr IN (1520, 1521, 1522, 1523)) AND
AccountInfo2 <> ''
GROUP BY dates.month_start, AccountInfo2, Description ;
您可以使用insert
或into
子句将其放入表中。这解决了主要问题,即生成一系列值。