2016-11-21 10 views
0

특정 연도의 등록 된 사용자 수를 월별로 그룹화하고자합니다. 다음은 내가 totalUsers를 들어, 이전 행의 결과를 추가하지 않는 올바른 결과를받지 못했습니다, 그러나 쿼리MySQL 사용자 정의 변수 COUNT와 함께 사용할 때 잘못된 결과를 반환합니다.

set @numberOfUsers := 0; 
SELECT month(from_unixtime(u.createdDate)) as month, count(u.id) as monthlyusers, 
(@numberOfUsers := @numberOfUsers + count(u.id)) as totalUsers 
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016' 
group by month(from_unixtime(u.createdDate)); 

입니다.

month | monthlyUsers | totalUsers 
10  |  1  |  1 
11  |  3  |  3 

11 번째 월의 총 사용자 수는 4 여야합니다. 쿼리에서 잘못된 부분을 확인하십시오. 도움이 되었습니까?

답변

1

당신은 최종 결과와 카운트가 여전히 "계산되어"있다되지 동안 누적 합계를 계산하는 하위 쿼리에 GROUP BY 쿼리를 embeed해야

set @numberOfUsers := 0; 
SELECT T.*, (@numberOfUsers := @numberOfUsers + T.monthlyusers) as totalUsers 
FROM 
(
    SELECT month(from_unixtime(u.createdDate)) as month, count(u.id) as monthlyusers 
    FROM user u 
    where year(from_unixtime(u.createdDate)) = '2016' 
    group by month(from_unixtime(u.createdDate)) 
) T; 
0

을 다음 읽기 : http://dev.mysql.com/doc/refman/5.7/en/user-variables.html

SELECT와 같은 다른 명령.에 대해서는 예상 한 결과를 얻을 수도 있지만 이것이 보장되는 것은 아 U니다. 다음과 같은 성명에서, 당신은 MySQL이 @a 첫째을 평가 것이라고 생각하고 두 번째 과제를 수행

SELECT month(from_unixtime(u.createdDate)) as month, 
     count(u.id) as monthlyusers, 
     (select count(*) from user USER where year(USER.createdDate)='2016' and month(USER.createdDate)<=month(u.createdDate)) as totalUsers 
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016' 
group by month(from_unixtime(u.createdDate)); 
:

다음 코드는 솔루션 (하위 쿼리 작업)로 작동합니다