0

不确定如何获取从今天开始的过去 12/13 个月内按动态月-年列分解的每个客户订单的总和

手动硬编码月份和定义年份可以正常工作,但无法动态显示

`Declare @SQLQuery as NVARCHAR(MAX)
Declare @PivotColumns as NVARCHAR(Max)

select @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME(DATENAME(MONTH, a.INVOICEDATE))
from dbo.TableA a,dbo.TableB b, dbo.TableC c
where a.INVOICEID=b.INVOICENUMBER and b.INVOICECUSTAC=c.CACCOUNT


set @SQLQUERY= N'select b.INVOICECUSTOMERACCOUNTNUMBER, c.ORGANIZATIONNAME, SUM(a.LINEAMOUNTTOTAL) [LineAmount]
from dbo.TableA a,dbo.TableB b, dbo.TableC c
where a.INVOICEID=b.INVOICENUMBER and b.INVOICECUSTAC=c.CACCOUNT 
group by b.INVOICECUSTAC,c.ORGANIZATIONNAME,a.INVOICEDATE) as x
PIVOT (SUM(LineAmount) FOR Month IN (' + @PivotColumns +')) AS P'

exec sp_executesql @SQLQUERY`

查询继续运行,不显示任何结果。

预期的结果应该是这样的:

CACCOUNT JULY-18 AUGUST-18.... AUGUST-19
ABC001 50000
DEF002 70000

4

1 回答 1

0

我认为您需要@PivotColumns用以下查询替换参数设置部分。

select @PivotColumns = 
        STRING_AGG (
                    (QUOTENAME ( (isnull( (DATENAME(MONTH, a.INVOICEDATE )), '')  ) ) ), 
                    ','
                  )
from    dbo.TableA a
            join dbo.TableB b on a.INVOICEID=b.INVOICENUMBER
            join dbo.TableC c on b.INVOICECUSTAC=c.CACCOUNT

Print @PivotColumns;
于 2019-08-27T15:42:07.803 回答