COUNT(DISTINCT月末

时间:2012-02-24 20:54:43

标签: mysql sql distinct

我有一个包含TSTAMP USERNAME SUBCR_TYPE和BALANCE日志的数据库。 我想知道每个月底有多少用户通过SUBSCR_TYPE获得积极的平衡

结果表应如下所示

         silver|gold|platinum
2011-09      34|56  |109
2011-10      23|43  |67
2011-11      33|56  |45
.
.
.

我试过这个明显错误的结果

SET @ts = unix_timestamp(LAST_DAY('2011-09-01'));
SELECT COUNT(DISTINCT USERNAME) AS 'silver'
FROM accLog_table 
WHERE BALANCE>=1 
AND SUBSCR_TYPE = 'silver'
AND TSTAMP<@ts

我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:0)

我很高兴发布一个适合我的解决方案

     SET @ts = unix_timestamp(LAST_DAY('2011-09-01'));       
     SET @subcr = 'silver';
            INSERT 
            INTO monthlyLiveAccess (
                timePeriod,
                silver
            )
            SELECT DATE_FORMAT(FROM_UNIXTIME(@ts), "%Y-%m") AS timePeriod,
                COUNT(*) AS silver FROM (
                SELECT t.* from(
                    SELECT DATE_FORMAT(FROM_UNIXTIME(DATE_TIME), "%Y-%m %H:%i:%s") AS "timePeriod", 
                    USERNAME, BALANCE
                    from accLog_table
                    WHERE N_BALANCE>1
                    AND DATE_TIME<@ts
                    AND SUBSCR='silver'
                ORDER BY timePeriod desc) as t
                GROUP BY USERNAME) AS t1
            ON DUPLICATE KEY UPDATE silver = VALUES(silver);