0

我想将 Null 改为 0 并在列和行的末尾添加小计。我该如何改变?

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

1 回答 1

0
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 ROLLUP一起处理coalesce(playerid, ''Column Total'')列总计,并sum(score) as row_total处理行总计。

于 2013-09-09T17:16:44.267 回答