我是一个非常新的SQL用户(我正在使用Microsoft SQL Server 2012)并且刚刚开始使用CASE
。我的最终目标是为每位客户提供1 ScoreDecile
。在下面的示例中,我已经能够创建CASE
语句来识别ScoreDecile
,但由于我的数据文件是每月(时间范围是1年),我显然为每个客户获得12个不同的分数。如何从最近一个月获得ScoreDecile
?非常感谢你的帮助!
SELECT
A.household_id
,SUM (a.contacted) AS Contacted
,CASE
WHEN (a.[Score] > 0.0740734327 AND a.[Score] < 1) THEN '1'
WHEN (a.[Score] > 0.051522993 AND a.[Score] < 0.0740722882) THEN '2'
WHEN (a.[Score] > 0.0410156448 AND a.[Score] < 0.051522951) THEN '3'
WHEN (a.[Score] > 0.0344048467 AND a.[Score] < 0.0410156323) THEN '4'
WHEN (a.[Score] > 0.029530965 AND a.[Score] < 0.0344046968) THEN '5'
WHEN (a.[Score] > 0.0254069538 AND a.[Score] < 0.0295309522) THEN '6'
WHEN (a.[Score] > 0.021865371 AND a.[Score] < 0.0254069523) THEN '7'
WHEN (a.[Score] > 0.0185329571 AND a.[Score] < 0.0218653642) THEN '8'
WHEN (a.[Score] > 0.0151799201 AND a.[Score] < 0.0185329032) THEN '9'
WHEN (a.[Score] > 0.0011824404 AND a.[Score] < 0.0151796708) THEN '10'
END AS 'ScoreDecile'
INTO
#temp2
FROM
[TABLE_A] A
LEFT OUTER JOIN
#TEMP B ON A.customerid = b.customerid
WHERE
A.[date] BETWEEN '2014-04-14' AND '2015-03-15'
GROUP BY
a.household_id, a.score
HAVING
SUM (a.contacted) = 0
ORDER BY
household_id
答案 0 :(得分:0)
如果您想获取当前日历月的数据,我猜您需要替换
A.[date] BETWEEN '2014-04-14' AND '2015-03-15'
带
A.[date] > DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)