我想为不同客户的到期值的数据创建数据透视表,并且我想将我的数据转移到3个透视时间段这样第一列就具有从今天到30天的期间的总票据现在在将来和第二个期间的应付价值((现在+ 30)<到期< 60) 并且下一个具有((Now + 60)< Due< 90)的值,并且最后一个具有今天到期的值。 这是我的代码,它获取我的原始数据:
SELECT [ADD].AccountID
,SUM(convert(money,ADDN.Amount - ISNULL(CollectedValue,0))) AS [Total Rest Amount]
,ADDN.DueDate AS [Due Date]
FROM [Accounting].[AccDocumentDetailsNotes] ADDN
INNER JOIN Accounting.AccDocumentDetails [ADD]
ON ADDN.AccDocumentDetailID = [ADD].ID
INNER JOIN Accounting.AccDocumentHeader ADH
ON ADH.ID = [ADD].AccDocumentHeaderID
INNER JOIN [Accounting].[AccNotesCollectors] ANC
ON ANC.NoteID = ADDN.ID
INNER JOIN Accounting.AccAccounts AA
ON AA.ID = [ADD].AccountID
GROUP BY [ADD].AccountID,ADDN.DueDate,[CodeTypePart],ADDN.Amount,CollectedValue
HAVING [CodeTypePart] = 'NR' AND convert(money,ADDN.Amount - ISNULL(CollectedValue,0)) > 0
这是结果的历史样本:
AccountID Total Rest Amount Due Date
----------- --------------------- -----------------------
25 6800.00 2017-02-23 17:31:09.000
25 1700.00 2017-02-23 17:31:09.000
25 10602.00 2017-05-28 16:28:14.000
27 14500.00 2017-02-28 14:53:57.000
30 120150.00 2017-02-24 00:23:20.000
30 117050.00 2017-02-24 00:23:20.000
33 2000.00 2017-04-04 20:48:51.193
45 39500.00 2017-04-18 20:13:46.000
45 31300.00 2017-04-18 20:13:46.000
45 9000.00 2017-04-18 20:13:46.000
45 32200.00 2017-04-22 16:38:47.803
46 32500.00 2017-02-23 20:14:24.000
46 15910.00 2017-02-23 20:14:24.000
答案 0 :(得分:1)
因此,您需要按照过期方式将数据细分为多个组,然后再进行调整。然后,为了获得总数,您可以将所有子列添加到一起。
select
AccountID,
isnull([90+],0)+isnull( [today 61-90],0)+ isnull( [today 31-60],0)+isnull( [today-30],0) total,
[90+], [today 61-90], [today 31-60], [today-30]
from
(
select AccountId, Amount,
CASE
WHEN datediff(d, duedate, getdate()) <= 30 THEN 'today-30'
when datediff(d, duedate, getdate()) between 31 and 60 then 'today 31-60'
when datediff(d, duedate, getdate()) between 61 and 90 then 'today 61-90'
else '90+'
END as daysoverdue
from @t
) src
pivot
( sum(Amount) for daysoverdue in ([90+], [today 61-90], [today 31-60], [today-30] ))p
答案 1 :(得分:1)
试试这个:
;with data as (
select
Today = cast(getdate() as date),
Plus30 = dateadd(d, 30, cast(getdate() as date) ),
Plus60 = dateadd(d, 60, cast(getdate() as date) ),
Plus90 = dateadd(d, 90, cast(getdate() as date) ),
EndOfTime = cast('21991231' as date),
t.*
from @t as t
)
select
AccountId,
Total = sum(Amount),
Due0To30 = sum(pvt.Due0To30),
Due31To60 = sum(pvt.Due31To60),
Due61To90 = sum(pvt.Due61To90),
Due91Plus = sum(pvt.Due91Plus)
from data
cross apply (values
(Today, Plus30, Amount, 0, 0, 0),
(Plus30, Plus60, 0, Amount, 0, 0),
(Plus60, Plus90, 0, 0, Amount, 0),
(Plus90, EndOfTime, 0, 0, 0, Amount)
)pvt(StartDate,EndDate,Due0To30, Due31To60, Due61To90, Due91Plus)
where [Due Date] >= pvt.StartDate
and [Due Date] < pvt.EndDate
group by AccountID