【发布时间】:2021-02-19 06:35:50
【问题描述】:
请您帮我开发计算客户评分的算法。 初始数据集和理想结果在下面的代码中。谢谢。
逻辑: 我们有客户和 6 个因素(值为 1 或 0(存在或不存在))。
我们应该计算客户的评分:
1(最大速率)- 客户拥有所有因素
2 - 客户有 1-5 个因数,但没有第 6 个
3 - 客户有因子 1-4 而没有因子 5(因子 6 无关紧要)
4 - 客户有因子 1-3 而没有因子 4(因子 5-6 无关紧要)
5 - 客户有 1-2 个因素,没有第 3 个因素(因素 4-6 无关紧要)
6 - 客户有因素 1 而没有因素 2(因素 3-6 无关紧要)
7 - 客户没有因素 1(因素 2-6 无关紧要)
关键是因素的数量有时会有所不同。
drop table if exists #tmp;
create TABLE #tmp (
[client] [nvarchar] null,
[factor1] [int] NULL,
[factor2] [int] NULL,
[factor3] [int] NULL,
[factor4] [int] NULL,
[factor5] [int] NULL,
[factor6] [int] null,
[desirable_result] [int] NULL
)
insert into #tmp (
[client]
,[factor1]
,[factor2]
,[factor3]
,[factor4]
,[factor5]
,[factor6]
,[desirable_result]
)
select '1', 1,1,1,1,1,1,1 union all
select '2', 1,1,0,1,1,1,5 union all
select '3', 1,0,1,1,0,1,6 union all
select '4', 1,1,1,1,1,0,2 union all
select '5', 1,1,1,0,0,1,4
此解决方案有效,但前提是因子数始终相等。 关键是因素的数量有时会有所不同。
select *
, "factor1" + "factor2" + "factor3" + "factor4" + "factor5" + "factor6" sum_6
, "factor1" + "factor2" + "factor3" + "factor4" + "factor5" sum_5
, "factor1" + "factor2" + "factor3" + "factor4" sum_4
, "factor1" + "factor2" + "factor3" sum_3
, "factor1" + "factor2" sum_2
, "factor1" sum_1
into #tmp2
from #tmp
select *
, case when sum_6 = 6 then 1 else
(case when sum_5 = 5 and sum_6 < 6 then 2 else
(case when sum_4 = 4 and sum_5 < 5 then 3 else
(case when sum_3 = 3 and sum_4 < 4 then 4 else
(case when sum_2 = 2 and sum_3 < 3 then 5 else
(case when sum_1 = 1 and sum_2 < 2 then 6 else
7
end)
end)
end)
end)
end)
end rate
from
#tmp2
【问题讨论】:
-
你使用的是
MySQL还是SQL Server? -
松鼠,我用的是 SQL Server 2017
-
您可以使用
CASE完成您想要的操作。它会有点难看,但它会工作 -
为什么只有
factor 1 to 3 with 1时client 5和result = 3 -
松鼠,感谢您的纠正和理解逻辑。客户 5 的结果应该是 4。我会在一分钟内更正我的帖子。
标签: sql tsql logic sql-server-2017