mysql 8 pivot 查询应该 return 一个非空值
mysql 8 pivot query should return a non null value
我希望以下数据透视查询显示值 0 而不是 null,
SELECT
pi.employeeId,
pi.Id,
MAX(CASE
WHEN pi.category = 'Repayment' THEN pi.value
WHEN isnull(pi.category) = 1 then 0
-- ELSE 0
END) as 'Repayment',
MAX(CASE
WHEN pi.category = 'Salary' THEN pi.value
ELSE 0
END) as 'Salary',
MAX(CASE
WHEN pi.category = 'Allowance' THEN pi.value
ELSE 0
END) as 'Allowance'
FROM
payData pi
GROUP BY pi.employeeId , pi.Id ;
上面的输出是,
employeeId Id Repayment Salary Allowance
121 2 2000 15000 1000
122 2 null 20000 2000
员工 ID 122 没有 还款 值,因此所需的输出是,
employeeId Id Repayment Salary Allowance
121 2 2000 15000 1000
122 2 0 20000 2000
我看不出需要二次分行还款case
。如果你想要 0
当类别不可用时,只需 else 0
:
SELECT
employeeId,
Id,
MAX(CASE WHEN category = 'Repayment' THEN value ELSE 0 END) as Repayment,
MAX(CASE WHEN category = 'Salary' THEN value ELSE 0 END) as Salary,
MAX(CASE WHEN category = 'Allowance' THEN value ELSE 0 END) as Allowance
FROM payData pi
GROUP BY employeeId, Id;
备注:
不要对标识符使用单引号!它们应该仅用于文字字符串,如 ANSI SQL 中指定并在所有数据库中都支持。
你有一个单一的table查询,所以所有列名的前缀不是强制性的
我希望以下数据透视查询显示值 0 而不是 null,
SELECT
pi.employeeId,
pi.Id,
MAX(CASE
WHEN pi.category = 'Repayment' THEN pi.value
WHEN isnull(pi.category) = 1 then 0
-- ELSE 0
END) as 'Repayment',
MAX(CASE
WHEN pi.category = 'Salary' THEN pi.value
ELSE 0
END) as 'Salary',
MAX(CASE
WHEN pi.category = 'Allowance' THEN pi.value
ELSE 0
END) as 'Allowance'
FROM
payData pi
GROUP BY pi.employeeId , pi.Id ;
上面的输出是,
employeeId Id Repayment Salary Allowance
121 2 2000 15000 1000
122 2 null 20000 2000
员工 ID 122 没有 还款 值,因此所需的输出是,
employeeId Id Repayment Salary Allowance
121 2 2000 15000 1000
122 2 0 20000 2000
我看不出需要二次分行还款case
。如果你想要 0
当类别不可用时,只需 else 0
:
SELECT
employeeId,
Id,
MAX(CASE WHEN category = 'Repayment' THEN value ELSE 0 END) as Repayment,
MAX(CASE WHEN category = 'Salary' THEN value ELSE 0 END) as Salary,
MAX(CASE WHEN category = 'Allowance' THEN value ELSE 0 END) as Allowance
FROM payData pi
GROUP BY employeeId, Id;
备注:
不要对标识符使用单引号!它们应该仅用于文字字符串,如 ANSI SQL 中指定并在所有数据库中都支持。
你有一个单一的table查询,所以所有列名的前缀不是强制性的