本帖最后由 SpeII 于 2022-6-27 14:41 编辑
写成了存储过程,你试试
[SQL] 纯文本查看 复制代码 DROP PROCEDURE
IF EXISTS sp_salary;
DELIMITER &&
CREATE PROCEDURE sp_salary ()
BEGIN
DECLARE
date_month_n VARCHAR (20) ;
DECLARE
count INT ;
DECLARE
i INT DEFAULT 0 ;
SET @s = 'SELECT NAME' ;
SET count = (
SELECT
COUNT(DISTINCT shouru)
FROM
tablename
) ;
WHILE i < count DO
SET date_month_n = (
SELECT
date_month
FROM
tablename
GROUP BY date_month
LIMIT i,
1
) ;
SET @s = CONCAT(
@s,
', MAX(CASE date_month WHEN ',
'\'',
date_month_n,
'\'',
' THEN shouru ELSE 0 END)',
' AS ',
'\'',
date_month_n,
'\''
) ;
SET i = i + 1 ;
END
WHILE ;
SET @s = CONCAT(
@s,
' FROM tablename GROUP BY name'
) ;
#SELECT @s;
PREPARE stmt
FROM
@s ; EXECUTE stmt ;
END&&
CALL sp_salary(); |