我希望你能提供帮助。我有一个状态更改日期列表以及该日期对象表的状态。我需要能够回答“在一个月内有多少人活跃”的问题
由于这是我之前使用的最复杂的SQL,所以我希望你不要介意我转向这个板子寻求帮助。如果我知道我在寻找什么,我可能会为自己解决,所以任何指针或链接都会受到赞赏。
这就是我的位置,以及输出的样子。请注意,这仅适用于“今天”,即Getdate()
,但我想将“今天”替换为2011年1月的所有月份结束。
--Begin common table expression - determine fields being brought back CLD data
with rankedValues (ConfirmedAmount, AccountNumber, PortfolioName, RankNumber, ProposalStatusName, StatusChangeDate, Determination) as
(
SELECT cld.ConfirmedAmount as Confirmed_Amount, cld.ProposalId as AccCount, blu.PortfolioName,
-- Rank AND de-dupe
Rank() over (partition by cld.AccountReference order by cld.owedamountid desc) as RankNumber, Pstat.ProposalStatusName, pstat.StatusChangeDate, det.Determination
FROM [tixdata].[dbo].[CLD_201305] cld
left outer join dbo.tblBookLookup blu on cld.BrandName = blu.BookName
left outer join [tixdata].[dbo].[PD_201305] pstat on CLD.ProposalId = pstat.ProposalId
left outer join dbo.DeterminationDateLookup det on cld.BrandName = det.Brand
Where Cld.BrandName <> 'Sold/Putback'
and cld.CurrentVersion = 1
--Remove any BKX double-counting
AND (cld.AccountReference not in (select distinct AccountNumber from BKX_201305))
)
--Fuigure out what is actually !"Active"
Select RV.Range as [True Status], COUNT(AccountNumber) AccountCount, PortfolioName
into #rv2
From(Select Case
When ProposalStatusName = 'Active' and GETDATE() > Determination then 'Active'
When ProposalStatusName = 'Pending Chairmans' and GETDATE() > Determination then 'Active'
When ProposalStatusName = 'Pending Review' and GETDATE() > Determination then 'Active'
When ProposalStatusName = 'Broken' and GETDATE() > Determination and GETDATE() < StatusChangeDate then 'Active'
When ProposalStatusName = 'Closed' and GETDATE() > Determination and GETDATE() < StatusChangeDate then 'Active'
Else 'Not_Active'
End as range, ConfirmedAmount, AccountNumber, PortfolioName, ProposalStatusName,StatusChangeDate, Determination From rankedValues
where RankNumber = 1) RV
Group by RV.Range, PortfolioName
--Consolidate
select * from #rv2 where [True Status] = 'Active'
drop table #rv2
当前输出:
True Status ¦ Account Count ¦ Portfolio Name
Active ¦ 10000 ¦ P1
Active ¦ 700 ¦ P2
Active ¦ 2000 ¦ P5
期望的输出:
Month ¦P1 ¦ P2 ¦P3
Jan 2011
Feb 2011
Mar 2011
.
.
.
Jun 2013
答案 0 :(得分:1)
如果您有月份(物理或构造)表,您可以进行交叉连接:
select
case when r.date < m.month then 'a' else 'b' end
from baseresults r
cross join months m
where m.month < GETDATE()
要从行到列获得投资组合,您必须使用PIVOT(参见http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx)