我被要求创建一个让债务人花费历史记录表的查询。
数据来源:MYOB Exonet 有父帐户,但该表是子帐户。但是,子帐户事务实际上并不在子级别进行交易 - 它们在父级别进行交易。但是我只希望报告一些子帐户。
表格如下:
DR_ACCS (debtor accounts)
有一个'视图'可以为子帐户提供交易。它不会出现在数据库中,但在输入查询时,它会显示为
AnaylticsSalesInvoices
DR_ACCS
和AnalyticsSalesInvoices
之间的联接是DR_ACCS.ACCNO = AnalyticsSalesInvoices.accountNumberAnalysis
。
所以,现在我需要“获取所有字段DR_ACCS.X_TOPCUSTOMER
勾选'Y'
的帐户的所有交易,并将它们拆分为'本月''上个月''2个月前''和'过去12个月'。“
我想要的是这样的结果:
> Customer Name | This Month | Last Month | 2 Months Ago | 12 Month |
> Jones | $235 | $756 | $49 | $2800 |
> Smith | $14 | $0 | $459 | $629 |
> Lewis | $520 | $35 | $0 | $9206 |
有人可以协助吗?我已经尝试了各种各样的方法并且丢失了!
答案 0 :(得分:0)
DECLARE
@this_start DATETIME,
@this_end DATETIME,
@last_start DATETIME,
@last_end DATETIME,
@l2_start DATETIME,
@l2_end DATETIME,
@year_start DATETIME,
@year_end DATETIME
SELECT
@this_start = DATEADD(m,DATEDIFF(m,0,GETDATE()),0),
@this_end = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)),
@last_start = DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)),
@last_end = DATEADD(s,-1,@this_start),
@l2_start = DATEADD(m,-2,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)),
@l2_end = DATEADD(s,-1,@last_start),
@year_start = DATEADD(m,-12,@this_start),
@year_end = @this_end
-- just a check of the variable values:
SELECT -- GETDATE() = 2014-09-15 10:50:15.000
@this_start, -- 2014-09-01 00:00:00.000
@this_end, -- 2014-09-30 23:59:59.000
@last_start, -- 2014-08-01 00:00:00.000
@last_end, -- 2014-08-31 23:59:59.000
@l2_start, -- 2014-07-01 00:00:00.000
@l2_end, -- 2014-07-31 23:59:59.000
@year_start, -- 2013-09-01 00:00:00.000
@year_end -- 2014-09-30 23:59:59.000
SELECT
dr_accs.NAME,
[This Month] = SUM(CASE WHEN b.date BETWEEN @this_start AND @this_end THEN b.total ELSE 0 END),
[Last Month] = SUM(CASE WHEN b.date BETWEEN @last_start AND @last_end THEN b.total ELSE 0 END),
[2 Months Ago] = SUM(CASE WHEN b.date BETWEEN @l2_start AND @l2_end THEN b.total ELSE 0 END),
[12 Month] = SUM(b.total)
FROM dr_accs JOIN AnalyticsSalesInvoices b ON DR_ACCS.ACCNO = b.accountNumberAnalysis
WHERE dr_accs.x_topcustomer = 'Y'
AND b.date_field BETWEEN @year_start AND @year_end
请注意,您必须更改' b.date'和'总计'到你的实际列名。