我有一条select语句,按月份将今年到目前为止的发票值拉出。我正在尝试添加一列以显示每个月的不同目标。因此,我可以每周或每月将实际值与目标进行比较。以下查询每月重复260000,如何将其更改为每月的其他货币值,或者在答案未知的地方显示零?
选择
格式(SUM(dbo.ARInvoices.arpInvoiceSubtotalBase,'C0')AS“总计”,
DATEPART(月,dbo.ARInvoices.arpInvoiceDate)作为“月”,“ 260000”作为目标
来自dbo.ARInvoices
dbo.ARInvoices.arpInvoiceDate> ='{%Current Year %%}'
按日期分组(月,dbo.ARInvoices.arpInvoiceDate)
得出的结果
理想情况下,结果将类似于以下内容:
MONTH TARGET ACTUAL
Jan $260000 $223735
Feb $383000 $69299
Mar $400000 $0
etc
答案 0 :(得分:1)
使用派生表/子查询/ cte计算每月总数,然后JOIN
到目标表
SELECT A.Total, A.Month, T.Target
FROM
(
SELECT SUM(dbo.ARInvoices.arpInvoiceSubtotalBase) AS Total
, DATEPART(month, dbo.ARInvoices.arpInvoiceDate) as Month
FROM dbo.ARInvoices
WHERE dbo.ARInvoices.arpInvoiceDate >= '{%Current Year%}'
GROUP BY DATEPART(month, dbo.ARInvoices.arpInvoiceDate)
) A
LEFT JOIN dbo.Targets T ON A.Month = T.Month