3

我正在使用 SQL Server。我需要使用的公式是 (Good-Bad)/Total_Responses。好的是当值 >=9 并且坏是 <=6 时。

我拥有的数据是:

DATE        Q1  Q2
2012-03-04   9   9
2012-03-04   8   8
2012-03-04   7   9
2012-03-04   4  NA
2012-03-04  10  10
2012-03-04   8   3
2012-03-04   3   4
2012-03-04   2   6
2012-03-04   6   8
2012-03-04  NA   6

我知道我将不得不使用“CASE WHEN ISNUMERIC(Q1)=1”来确保它不使用 NA 值(它们存储为 Nvarchar)

所以公式最终会是 (5-8)/18=-0.16666 所以总的来说,我试图让数据看起来像:

DATE        Promotor_Score
2012-03-04        -0.16666

谢谢你!

4

2 回答 2

4

这行得通吗?

SELECT  Date,
        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)) AS float)
        / (SUM(CASE WHEN ISNUMERIC(Q1) != 1 THEN 0
                   ELSE 1 END)
        + SUM(CASE WHEN ISNUMERIC(Q2) != 1 THEN 0
                   ELSE 1 END))
FROM    Questions
GROUP BY Date

或者,如果 'NA' 是唯一的非数字值,请显式测试它。

于 2012-04-30T15:24:05.207 回答
0

在@DavidM 回答的基础上,我添加了浮点转换和 Q2 列意识:

SELECT [date], 
1e0 -- a float multiplier to avoid integer value
* SUM( 0
    -- get the positive, negative or neutral from q1
    + 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
    -- get the positive, negative or neutral from q2
    + 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( 0
    -- get the number of valid questions from q1
    + CASE WHEN ISNUMERIC(q1) != 1 THEN 0 ELSE 1 END        
    -- get the number of valid questions from q2
    + CASE WHEN ISNUMERIC(q2) != 1 THEN 0 ELSE 1 END
)
FROM Questions
GROUP BY Date;
于 2012-04-30T15:34:13.623 回答