根据交易量为数据分配分数

时间:2016-12-14 00:56:36

标签: sql-server tsql

我正在尝试实施一个查询,为成员分配分数但不能这样做。

在下面的示例中,成员数是10,但我希望计数是动态的,我已经通过

完成了
SELECT COUNT (DISTINCT [Member No])
FROM Table

表格结构:

MemberNo    nvarchar(255)
TransactionDate    datetime
SalesNumber    int
SalesAmount    money
DateCreated    datetime

在示例中

Member 1  - 5 Transactions
Member 2  - 5 Transactions
Member 3  - 10 Transactions
Member 4  - 10 Transactions
Member 5  - 100 Transactions
Member 6  - 100 Transactions
Member 7  - 15 Transactions
Member 8  - 15 Transactions
Member 9  - 2 Transactions
Member 10 - 2 Transactions

我希望看到:

Top 20 % =  Member 5 and Member 6. They will each get a Score = 5
Next 20 % = Member 7 and Member 8. They will each get a Score = 4
Next 20% = Member 3  and Member 4. They will each get a Score = 3
Next 20% = Member 1 and Member 2. They will get a Score = 2
Last 20% = Member 9 and Member 10. They will get a Score = 1

1 个答案:

答案 0 :(得分:1)

一种选择是使用CTE并计算每个成员的五分位数。为这么多子查询道歉,但这是将每个成员变成五分之一的最简洁方法。

WITH cte AS (
    SELECT [Member No] AS memberNo,
           COUNT (*) AS memberCount
    FROM Table
    GROUP BY [Member No]
)
SELECT CASE WHEN t.rank < 0.2 THEN "first quintile"
            WHEN t.rank >= 0.2 AND t.rank < 0.4 THEN "second quintile"
            WHEN t.rank >= 0.4 AND t.rank < 0.6 THEN "third quintile"
            WHEN t.rank >= 0.6 AND t.rank < 0.8 THEN "fourth quintile"
            ELSE "fifth quintile"
       END AS quartile,
       t.memberNo,
       t.memberCount
FROM
(
    SELECT t.memberNo,
           t.memberCount,
           CAST(t.rn AS FLOAT) / CAST((SELECT COUNT(*) FROM cte) AS FLOAT) AS rank
    FROM
    (
        SELECT memberNo,
               memberCount,
               ROW_NUMBER() OVER (ORDER BY memberCount DESC) AS rn
        FROM cte
    ) t
) t
ORDER BY t.memberCount DESC