日期:2014-05-17 浏览次数:20590 次
CREATE TABLE [dbo].[xs](
[rq] [date] NULL,
[SPID] [int] NOT NULL,
[je] [decimal](38, 2) NULL
) ON [PRIMARY]
GO
DECLARE @loop INT
DECLARE @rq DATETIME
DECLARE @je DECIMAL(20,2)
SET @rq = CONVERT(VARCHAR(10),DATEADD(MONTH,-3,GETDATE()),121)
WHILE @rq < GETDATE()
BEGIN
SELECT @loop = 1
WHILE @loop <= 200
BEGIN
SELECT @je = RAND() * 1000.00,@loop = @loop + 1
INSERT INTO XS (rq,SPID,je) VALUES(@rq,@loop,@je)
END
SET @rq = DATEADD(DAY,1,@rq)
END
--是否这个意思?
;with cte_test
as
(
select *, rowid= row_number() over (partition by spid order by je desc)
,cnt = (select count(*) from xs where spid=a.spid and rq between dateadd(month,-3,getdate()) and getdate())
from xs as a
where rq between dateadd(month,-3,getdate()) and getdate()
)
select
rq,spid,je,
type= case when rowid <= 0.8 * cnt then 'A'
when rowid>0.8*cnt and rowid<= 0.95*cnt then 'B'
else 'C' end
from cte_test
declare @c decimal(38,2)
select @c=sum(je) from xs
;with c1 as(
select *,rn=row_number()over(order by je desc),0 as s from xs
),c2 as(
select rq,spid,je,rn,je as s,'a' as flg from c1 where rn=1
union all
select a.rq,a.spid,a.je,a.rn,a.je+b.s as s,
(case when a.je+b.s<@c*0.8 then 'a' when a.je+b.s<0.95 then 'b' else 'c' end) as flg
from c1 a inner join c2 b on a.rn=b.rn+1 where a.s=0 and b.s>0
)
select rq,spid,je,flg from c2 OPTION (MAXRECURSION 0)