我正在使用SQL Server 2000.我正在尝试根据以下公式计算净推荐分数或NPS
公式 :(Promoters - Detractors) / Total Questions
我有以下数据:
Time Q1 Q2 Q3
----------- ------ ------ ------
2012-03-14 7 7 5
2012-03-15 3 2 5
2012-03-15 7 NA 2
2012-03-15 9 10 NULL
2012-03-15 8 4 4
2012-03-15 NA 6 4
2012-03-16 1 7 4
2012-03-16 NULL 0 5
2012-03-17 9 9 2
2012-03-19 0 0 1
2012-03-19 8 5 4
2012-03-19 1 0 3
最初编写数据库的人将NULL
值存储为 NVARCHAR 格式的空白或NA enter code here
(只有上帝知道为什么......)所以查询我是玩现在使用 ISNUMERIC ,我试图不计算空白或NA值。
我的查询无法正常工作,如下所示:
SELECT CAST(SUM(CASE WHEN ISNUMERIC([Q1]) != 1 THEN 0
WHEN CAST([Q1] AS int) >= 9 THEN 1
WHEN CAST([Q1] AS int) <= 6 THEN -1
ELSE 0 END)
+ SUM(CASE WHEN ISNUMERIC([Q2]) != 1 THEN 0
WHEN CAST([Q2] AS int) >= 9 THEN 1
WHEN CAST([Q2] AS int) <= 6 THEN -1
ELSE 0 END)
+ SUM(CASE WHEN ISNUMERIC([Q3]) != 1 THEN 0
WHEN CAST([Q3] AS int) >= 9 THEN 1
WHEN CAST([Q3] AS int) <= 6 THEN -1
ELSE 0 END)
AS FLOAT)
/ (SUM(CASE WHEN ISNUMERIC([Q1]) != 1 THEN 0
ELSE 1 END)
+ SUM(CASE WHEN ISNUMERIC([Q2]) != 1 THEN 0
ELSE 1 END)
+ SUM(CASE WHEN ISNUMERIC([Q3]) != 1 THEN 0
ELSE 1 END)
) as [NPS]
FROM [nps]
有人能指出我正确的方向吗? 谢谢!
答案 0 :(得分:2)
正如其他人指出的那样,将列的数据类型从NVARCHAR
更改为INT
将是理想的选择。
以下是可帮助您获得所需结果的查询。
Click here to view the demo in SQL Fiddle using SQL Server 2012
脚本:
SELECT
(
SUM (CASE WHEN q >= 9 THEN 1. END) -
SUM (CASE WHEN q <= 6 THEN 1. END)
) /
SUM (1.) AS nps
FROM
(
SELECT (CASE
WHEN ISNUMERIC(q1) <> 1 THEN 0.
ELSE CAST(q1 AS FLOAT)
END) AS q
FROM [nps]
UNION ALL
SELECT (CASE
WHEN ISNUMERIC(q2) <> 1 THEN 0.
ELSE CAST(q2 AS FLOAT)
END) AS q
FROM [nps]
UNION ALL
SELECT (CASE
WHEN ISNUMERIC(q3) <> 1 THEN 0.
ELSE CAST(q3 AS FLOAT)
END) AS q
FROM [nps]
) nps;
输出:
np
---------
-0.611111
答案 1 :(得分:0)
如何修复数据库?如果该值实际为0,是否存在NA或空白被错误表示的情况?如果没有,将所有空格和NA转换为0,将列数据类型更改为int,不允许为null。然后你的生活变得更加简单。
答案 2 :(得分:0)
不要乱用你的数据类型。要么改变架构,要么本地处理它们。
SELECT
SUM(
CASE WHEN [Q1] IN ( '9', '10') THEN 1.0
WHEN [Q1] IN ('7', '8', 'NA') THEN 0.0
WHEN [Q1] IS NULL THEN 0.0
ELSE -1.0 END
+ CASE WHEN [Q2] IN ( '9', '10') THEN 1.0
WHEN [Q2] IN ('7', '8', 'NA') THEN 0.0
WHEN [Q2] IS NULL THEN 0.0
ELSE -1.0 END
+ CASE WHEN [Q3] IN ( '9', '10') THEN 1.0
WHEN [Q3] IN ('7', '8', 'NA') THEN 0.0
WHEN [Q3] IS NULL THEN 0.0
ELSE -1.0 END
)
/
SUM(
CASE WHEN [Q1] <> 'NA' THEN 1.0 ELSE 0.0 END
+ CASE WHEN [Q2] <> 'NA' THEN 1.0 ELSE 0.0 END
+ CASE WHEN [Q3] <> 'NA' THEN 1.0 ELSE 0.0 END
) AS [nps]
FROM
[nps]
除数很简单;如果[Qn]值为NULL,则测试失败并返回0.0:)
您还可以通过始终使用NULL
代替'NA'
来进一步简化,而无需更改架构。