获取动态列的总和

时间:2019-09-06 11:46:37

标签: sql-server tsql

我试图在最后显示一列,以显示动态月份列的总和。目前,我正在获得显示从今天开始的最近12个月的列,但我希望最后一列显示这些值的最终总和。

declare @start DATETIME = (select  DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-12, 0)) 
declare @end DATETIME = (select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
declare @v_columns varchar(max)
declare @v_sql varchar(max)


;with months (v_date)
AS
(
    SELECT @start
    UNION ALL
    SELECT DATEADD(month,1,v_date)
    from months
    where DATEADD(month,1,v_date)<=@end
)
select @v_columns=stuff((select','+QUOTENAME(DATENAME(month,v_date)+cast(year(v_date) as varchar)) from months for xml path('')),1,1,'')
--print @v_columns
set @v_sql='
;with months (v_date)
AS
(
    SELECT cast('''+convert(varchar(10),@start,101)+''' as date)
    UNION ALL
    SELECT DATEADD(month,1,v_date)
    from months
    where DATEADD(month,1,v_date)<='''+convert(varchar(10),@end,101)+'''
)
SELECT 
ITEMNUMBER,PRODUCTDESCRIPTION,PRODUCTGROUP_CUSTOM,PRODUCTLIFECYCLESTATEID,PRIMARYVENDORACCOUNTNUMBER,ALTERNATIVEITEMNUMBER,ORDEREDQUANTITY,WAREHOUSELOCATIONID,DATAAREAID,AVAILABLEONHANDQUANTITY'+@v_columns+'
FROM 
(


SELECT 
b.ITEMNUMBER,d.PRODUCTDESCRIPTION,b.PRODUCTGROUP_CUSTOM,b.PRODUCTLIFECYCLESTATEID,b.PRIMARYVENDORACCOUNTNUMBER,b.ALTERNATIVEITEMNUMBER,e.ORDEREDQUANTITY,c.WAREHOUSELOCATIONID,b.DATAAREAID,e.AVAILABLEONHANDQUANTITY, SUM(ISNULL(a.QTY,0)) [LineAmount],DATENAME(month,a.invoicedate)+cast(year(a.invoicedate) as varchar) as v_date
from dbo.Table1 b

inner join Table2 a
on a.ITEMID=b.ITEMNUMBER
inner join Table3 c
on b.itemnumber=c.ITEMNUMBER
inner join Table4 d
on b.ITEMNUMBER=d.PRODUCTNUMBER
inner join Table5 e
on b.ITEMNUMBER=e.ITEMNUMBER
where a.DATAAREAID=b.DATAAREAID 
group by b.ITEMNUMBER,d.PRODUCTDESCRIPTION,b.PRODUCTGROUP_CUSTOM,b.PRODUCTLIFECYCLESTATEID,c.WAREHOUSELOCATIONID,b.DATAAREAID,e.AVAILABLEONHANDQUANTITY,e.ORDEREDQUANTITY,a.invoicedate,b.PRIMARYVENDORACCOUNTNUMBER,b.ALTERNATIVEITEMNUMBER) as x
PIVOT
(
 SUM(LineAmount) FOR v_date IN ('+@v_columns+')
) PVT'

print @v_sql
EXEC (@v_sql)

0 个答案:

没有答案