撰写查询并给出分数

时间:2016-12-20 07:19:02

标签: sql-server sql-server-2008

我正在尝试为以下内容编写查询:

计算过去90天内的交易次数。注意:这需要 平均为新成员=(交易数量/天数为a 成员)x 90

新成员是DateCreated从今天起0到90天之间的成员。

表格结构:

Column Name         Datatype
---------------------------------
Member_No           nvarchar(255)
Order_No            int
Transaction_Date    datetime 
Net                 money
Date_Created        datetime

此外,最后一步是在计算交易后,我需要给出一个分数。因此,如果一名成员的数量超过8,则得分为5。

以下是范围:`

Transaction count      Score
      >8                  5
      6-8                 4
      4-6                 3
      2-4                 2
      0-2                 1

如果有任何疑问,请告诉我

2 个答案:

答案 0 :(得分:0)

希望以下代码适合您(未经过测试,因为没有Schema。)

;WITH RANKS AS 
(
    SELECT 0 AS FROM_TR, 2 AS TO_TR, 1 AS SCORE
    UNION ALL
    SELECT 3 AS FROM_TR, 4 AS TO_TR, 2 AS SCORE
    UNION ALL
    SELECT 5 AS FROM_TR, 6 AS TO_TR, 3 AS SCORE
    UNION ALL
    SELECT 7 AS FROM_TR, 8 AS TO_TR, 4 AS SCORE
    UNION ALL
    SELECT 9 AS FROM_TR, NULL AS TO_TR, 5 AS SCORE 

)
, MEMBER_TRANS AS (
SELECT Member_No AS MEMBER_NO
    ,Date_Created AS DATE_CREATED
    ,COUNT(DISTINCT Order_No) ACTUAL_TRANSACT_COUNT
    ,CASE 
        WHEN Date_Created BETWEEN DATEADD(DD, - 90, GETDATE())
                AND GETDATE()
            THEN CAST(
            COUNT(DISTINCT Order_No) / DATEDIFF(DD, Date_Created, GETDATE()) * 90 
            AS INT)
        ELSE COUNT(DISTINCT Order_No)
        END AS TRANSACT_COUNT
FROM TABLE1
WHERE Transaction_Date BETWEEN DATEADD(DD, - 90, GETDATE())
        AND GETDATE()
GROUP BY Member_No
    ,Date_Created
)

SELECT MT.Member_No,MT.TRANSACT_COUNT, R.SCORE  FROM MEMBER_TRANS MT
INNER JOIN RANKS R ON MT.TRANSACT_COUNT BETWEEN R.FROM_TR 
AND isnull(R.TO_TR,MT.TRANSACT_COUNT)

--Added Extra below code from your comments

UNION ALL

SELECT Member_No,COUNT(DISTINCT Order_No), 1 AS SCORE FROM TABLE1
WHERE Transaction_Date < DATEADD(DD, - 90, GETDATE())
AND  Transaction_Date NOT BETWEEN DATEADD(DD, - 90, GETDATE())
AND GETDATE()
GROUP BY Member_No

答案 1 :(得分:0)

代码将根据您的要求返回所需的结果。请找到以下查询的输出快照。 enter image description here

 WITH Mycte
AS
(
Select Member_No,Case when DateDiff(dd,Date_Created,Getdate())>90 then 0 else 1 END AS New_Member
, DateDiff(dd,Date_Created,Getdate()) AS DaysAsMember
,Count(Order_No) TransactionCount from #Sample1
group by Member_No,Date_Created
)
Select Member_No,Case when TransactionCount > 8 THEN 5
        WHEN TransactionCount BETWEEN 6 AND 8 THEN 4
        WHEN TransactionCount BETWEEN 4 AND 5 THEN 3
        WHEN TransactionCount BETWEEN 3 AND 4 THEN 2
        WHEN TransactionCount BETWEEN 0 AND 2 THEN 1
        END
        AS Score
From Mycte