CASE语句在SQL中不能正常工作

时间:2016-08-04 19:53:12

标签: mysql sql count case

SELECT  userid,                                                                                         
  (SELECT CASE WHEN (COUNT(CASE WHEN casinowagers != 0
          THEN 1
            ELSE null
          END)
                + COUNT(CASE WHEN depositmade_amt != 0
                        THEN 1
                            ELSE null
                        END)) >= 3  
        AND (Round(sum(totalhold - playercomps - freemoney - (depositmade_amt*.1)),2)) >= 10
                THEN "VIP"
                    ELSE "NON-VIP"
                END as VIPcheck 
    FROM player_activity        
    WHERE YEAR(txndate) = YEAR(CURRENT_DATE - INTERVAL 3 MONTH)
        AND MONTH(txndate) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH)         
    ) as vipMonthStatus,            
    (COUNT(CASE WHEN casinowagers != 0
            THEN 1
            ELSE null
            END) 
                + COUNT(CASE WHEN depositmade_amt != 0
                        THEN 1
                            ELSE null
                        END)) as activityCount, 
    (Round(sum(totalhold - playercomps - freemoney - (depositmade_amt*.1)),2)) as Value,                        
FROM player_activity
WHERE userid = 2023410 
GROUP BY year(txndate),month(txndate)  
LIMIT 1000

所以基本上vipMonth状态总是以“VIP”的形式返回。但是,对于5月份(因为下面的“where”声明),它应该是“非贵宾”,因为只有1次存款和1次下注。

是什么给出了?

( WHERE YEAR(txndate) = YEAR(CURRENT_DATE - INTERVAL 3 MONTH)
        AND MONTH(txndate) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH) )

1 个答案:

答案 0 :(得分:0)

您需要将vipMonthStatus子查询中的player_activity表绑定到主查询中的player_activity表。

首先别名"内部" player_activity和"外部" player_activity表,以便您可以区分它们。像in_player_activity和out_player_activity之类的东西。

然后,您需要向vipMonthStatus子查询添加一个额外的WHERE语句,以根据userid将内部表中的记录限制为外部表中的关联记录。最终看起来像这样:

FROM player_activity in_player_activity     
WHERE YEAR(in_player_activity.txndate) = YEAR(CURRENT_DATE - INTERVAL 3 MONTH)
    AND MONTH(in_player_activity.txndate) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH)  
    AND in_player_activity.userid = out_player_activity.userid 

请记住,您已经引入了表别名,您需要将别名前缀添加到所有其他列名称中。就个人而言,我会使用像opa和ipa这样简洁的东西。