1

我希望你能帮忙。我有一个对象表的状态更改日期列表和该日期的状态。我需要能够回答“给定月份有多少人活跃”这个问题

由于这是我以前使用过的最复杂的 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
4

1 回答 1

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

于 2013-06-28T12:42:41.800 回答