今天写业务的时候遇到一个查询,废话不多说,原数据表结构如下:


Rule字段实际上是一个枚举的值,最终业务需求是将Rule行转为多列,然后值为原数据表的Value字段
SQL如下:
SELECT
Point,
Platform,
[0] as 'Overseas',
[100] as 'Conventional',
[200] as 'Rigorous'
FROM [dbo].[PB_ShieldingPoint] as sp PIVOT(MAX([Value]) for [Rule] in ([0],[100],[200])) as p
结果:

已经成功把行转为列了,之后再GroupBy一下按照Point进行分组就可以了,最终SQL如下:
SELECT
Point,
Platform,
MAX(Conventional) as Conventional,
MAX(Rigorous) as Rigorous,
MAX(Overseas) as Overseas
FROM
(
SELECT
Point,
Platform,
[0] as 'Overseas',
[100] as 'Conventional',
[200] as 'Rigorous'
FROM [dbo].[PB_ShieldingPoint] as sp PIVOT(MAX([Value]) for [Rule] in ([0],[100],[200])) as p
) g
GROUP BY Point,Platform
ORDER BY Point,Platform
结果:

与最终业务要求一致:

MySql没有这个函数,如果需要行转列可以参考这篇文章