MySQL循环每周总分

时间:2014-09-11 19:32:43

标签: mysql

以下语句输出userNameweek1Score。我希望它循环17次,以获得17周中每一个的得分。

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... |
+------------------------------------------------------------------------+

我如何使用MySQL循环来执行此操作?

1 个答案:

答案 0 :(得分:0)

我认为您的查询有点复杂。但是,有一种更好的方法:Pivot Query。

MySQL没有“pivot”指令,但可以构建表达式来获得所需的输出。

我将构建一个临时表,使事情更容易阅读(我使用用户变量使事情更清晰):

-- 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;

有点费力,但我认为这会给你所需要的。希望它有所帮助。