简体   繁体   English

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

[英]change mysql pivot table code into php

I want to instead Null to 0 and add subtotal at the end of column and row. 我想将Null改为0,并在列和行的末尾添加小计。 how can I change? 我该如何改变?

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

SET @sql = CONCAT('SELECT playerid, ', @sql, '
              FROM scores
               GROUP BY playerid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
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;

The else 0 takes care to deliver 0 instead of null. else 0注意传递0而不是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. WITH ROLLUPcoalesce(playerid, ''Column Total'')负责列的总数,而sum(score) as row_total负责行的总数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM