日期:2014-05-18 浏览次数:20658 次
declare @importantLead table
(
custID int,
amount decimal(18,0),
ownerID int,
deptID int
)
declare @importantLead table
(
custID int,
amount decimal(18,0),
ownerID int,
deptID int
)
insert @importantLead
select 1,20,1,1 union all
select 1,24,2,1 union all
select 2,52,2,2 union all
select 3,96,1,3 union all
select 3,45,3,3 union all
select 3,96,3,3 union all
select 3,34,4,3 union all
select 3,18,2,3
declare @total float
set @total=(select SUM(amount) from @importantLead)
declare @sum float
set @sum=(select SUM(amount) from
(select top 4 amount from @importantLead order by amount desc)a)
if (@sum/@total)>=0.6
select count(distinct custID) as 重要客户数 from(
select top 4 custID from @importantLead order by amount desc)b
/*
重要客户数
2
*/
------解决方案--------------------
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba')
BEGIN
DROP TABLE tba
END
GO
CREATE table tba
(
custID int,
amount decimal(18,0),
ownerID int,
deptID int
)
INSERT INTO tba
SELECT 1,1000,1,1 UNION
SELECT 2,2000,1,1 UNION
SELECT 3,5000,1,1 UNION
SELECT 4,1000,1,1 UNION
SELECT 5,500,1,1 UNION
SELECT 6,100,1,1 UNION
SELECT 7,100,1,1 UNION
SELECT 8,100,1,1 UNION
SELECT 9,0,1,1 UNION
SELECT 10,0,1,1 UNION
SELECT 11,0,1,1
GO
WITH tbb AS
( SELECT custID,amount,ownerID,deptID,RN=ROW_NUMBER() OVER (ORDER BY amount Desc) FROM tba
)
SELECT custID,(SELECT SUM(amount) FROM tbb AS B WHERE A.RN >= B.RN) AS amount,(SELECT SUM(amount) FROM tbb AS B WHERE A.RN >= B.RN)/(SELECT SUM(amount) FROM tbb) AS Proportion
FROM tbb AS A
custID amount Proportion
3 5000 0.510204
2 7000 0.714285
1 8000 0.816326
4 9000 0.918367
5 9500 0.969387
6 9600 0.979591
7 9700 0.989795
8 9800 1.000000
9 9800 1.000000
10 9800 1.000000
11 9800 1.000000