2014-09-11 2 views
2

다음 문은 userNameweek1Score을 출력합니다. 나는 17 번 반복하여 각 17 주 동안 점수를 얻고 싶습니다.매주 총점에 대한 MySQL 루프

SELECT userName, (totalWins+(totalPushs*.5)) AS week1Score FROM (
    SELECT *, SUM(win) AS totalWins, SUM(lost) AS totalLost, SUM(push) AS totalPushs FROM (
     SELECT *, (finalResult = 'win') AS win, (finalResult = 'loss') AS lost, (finalResult = 'push') AS push FROM (
      SELECT userName, IF (pickID=visitorID, visitorResult, homeResult) AS finalResult 
      FROM table_users 
      JOIN table_picks 
      ON table_users.userID = table_picks.userID 
      JOIN table_schedule 
      ON table_picks.gameID = table_schedule.gameID 
      WHERE weekNum = 1 
     ) x 
    ) x GROUP BY userName 
) x ORDER BY userName 

위의 명령문은 다음을 출력합니다.

+-----------------------+ 
| userName | week1Score | 
+-----------------------+ 

17 번 반복하여 다음과 같이 출력하고 싶습니다.

+------------------------------------------------------------------------+ 
| userName | week1Score | week2Score | week3Score | week4Score | week... | 
+------------------------------------------------------------------------+ 

어떻게하면이 작업을 수행 할 수 있습니까?

답변

0

질문이 약간 복잡하다고 생각합니다. 그러나 피벗 쿼리 (Pivot Query)라는 더 나은 방법이 있습니다.

MySQL에는 "피벗"명령어가 없지만 필요한 출력을 얻기 위해 표현식을 작성할 수 있습니다.

-- This first table will compute the score 
drop table if exists temp_step01; 
create temporary table temp_step01 
select userId 
    , userName 
    , weekNum 
    , @finalResult := if(pickId=visitorId, visitorResult, homeResult) as finalResult 
    , @w := @finalResult = 'win' as win 
    , @l := @finalResult = 'loss' as lost 
    , @p := @finalResult = 'push' as push 
    , @w + (@p * 0.5) as score 
from 
    table_users as tu 
    join table_picks as tp on tu.userId = tp.userId 
    join table_schedule as ts on tp.gameId = ts.gameId; 
alter table temp_step01 
    add index uid(userId), 
    add index wn(weekNum); 

이제 재미있는 부분 :

나는 좀 더 쉽게 일이 (내가 좀 더 명확 물건을 만들기 위해 사용자 변수를 사용하고 있습니다) 읽을 수 있도록하기 위해 임시 테이블을 만들 수 있습니다 피벗 테이블을 구축

-- First, build the expression for each column 
select 
    group_concat(
     concat(
     'sum(case weekNum when ', weekNum, ' then score end) as week', weekNum, 'score' 
    ) 
    ) 
into @sql 
from (select distinct weekNum from temp_step01) as a; 
-- Then, create a complete SELECT statement 
set @sql = concat('select userId, userName, ', @sql, ' from temp_step01 group by userId'); 
-- OPTIONAL: Check that the sql statement is well written: 
select @sql; 
-- Now, prepare a statement, and execute it 
prepare stmt from @sql; 
execute stmt; 
-- When you're done, don't forget to deallocate the statement 
deallocate prepare stmt; 

조금 힘들 겠지만, 나는 이것이 당신에게 필요한 것을 줄 것이라고 생각합니다. 희망이 도움이됩니다.

+0

userId '에 의해 temp_step01 그룹의'@sql '근처에 SQL 구문 오류가 발생했습니다.') '' – locnguyen

+0

죄송합니다. 쉼표를 놓으 셨습니다. 바로 수정했습니다. – Barranka

+0

결과는 제가 얻은 결과입니다. @ sql' value'userId, userName, sum (case weekNum이 1 t 일 때 ... 선택하십시오.)이게 무엇인지 생각하고 있지만 그게 내가 찾고있는 것이 아닌지 확실하지 않은 경우 – locnguyen