且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将mysql数据透视表代码更改为php

更新时间:2023-02-26 10:11:40

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
  'sum(case when gameid = ''',
  gameid,
  ''' then score else 0 end) AS ''',
  gameid, ''''
)
  ) INTO @sql
FROM  scores;

SET @sql = CONCAT('SELECT coalesce(playerid, ''Column Total'') as playerid, ', @sql, ', sum(score) as row_total
              FROM scores
               GROUP BY playerid WITH ROLLUP');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

else 0 负责传递 0 而不是 null.WITH ROLLUPcoalesce(playerid, ''Column Total'') 一起处理列总数,而 sum(score) as row_total 负责行总计.

The else 0 takes care to deliver 0 instead of null. The WITH ROLLUP together with the coalesce(playerid, ''Column Total'') takes care of the column totals, and the sum(score) as row_total takes care of the row totals.