需要有关SQL Server存储过程的格式输出的帮助。
我想在每月30日的每一天循环检查发票金额。
这是我的代码
Declare @SDate Date
Declare @EDate Date
SET @SDate = '2014-11-01'
SET @EDate = '2014-11-30'
WHILE @SDate <= @EDate
BEGIN
--print @SDate
select
(select sum(amt)
from VEntry
where ACode = '111111' and Source = 'AP_DOC_AMT'
and VDate = @SDate) as INV,
(select sum(AFDisAmt)
from DO_Item
where Client_No = '999999'
and DO_Date = @SDate) as INV_T
SET @SDate = DATEADD(D,1,@SDate)
END
此代码正在运行,但输出显示每天的标题。
我想只显示一个标题作为正常输出。
答案 0 :(得分:2)
根本不需要任何循环。只需使用BETWEEN获取所有日期的数据,并将结果与FULL OUTER JOIN一起加入:
Declare @SDate Date
Declare @EDate Date
SET @SDate = '2014-11-01'
SET @EDate = '2014-11-30'
SELECT COALECE(VEntries.VDate, DO_Items.DO_Date) AS Date
VEntries.Amount,
DOData.Amount
FROM
(select VDate,
sum(amt) AS Amount
from VEntry
where ACode = '111111'
and Source = 'AP_DOC_AMT'
and VDate BETWEEN @SDate AND @EDate
group by VDate) AS VEntries
FULL OUTER JOIN
(select DO_Date,
sum(AFDisAmt) AS Amount
from DO_Item
where Client_No = '999999'
and DO_Date BETWEEN @SDate AND @EDate
group by DO_Date) AS DO_Items
ON VEntries.VDate = DO_Items.DO_Date
答案 1 :(得分:1)
如果你有一个日期值表(一种方法是使用下面的递归cte),你可以left join
和group by
来获得你想要的结果。
Declare @SDate Date
Declare @EDate Date
SET @SDate = '2014-11-01'
SET @EDate = '2014-11-30'
;with cte
as
( select @SDate as iDate
UNION ALL
select dateadd(day,1,iDate) as iDate from
cte
where iDate < @EDate
)
select iDate as Date, ISNULL(sum(amt),0) as INV , ISNULL(sum(AFDisAmt),0) as INV_T
from cte
left join VEntry
on cte.iDate = VEntry.VDate
and ACode = '111111' and Source = 'AP_DOC_AMT'
left join DO_Item
on cte.iDate = DO_Item.DO_Date
and Client_No = '999999'
group by cte.iDate