1.实现方式
sql行列转置两种写法
- case when
完整语法
case [col] when [value1] then [value2] else [value3] end
case when [条件语句] then [value1] else [value2] end - if
完整语法 if([条件语句], [value1], [value2])
2.示例
SELECT
DATE_FORMAT( d.date, ‘%Y-%m‘ ) AS 月份,
IF
( d.series_id = 4974, sum( d.new_sheng ), 0 ) AS `理想ONE`,
IF
( d.series_id = 11, sum( d.new_sheng ), 0 ) AS `11`,
IF
( d.series_id = 22, sum( d.new_sheng ), 0 ) AS `22`,
IF
( d.series_id = 33, sum( d.new_sheng ), 0 ) AS `33`
FROM
dy_series_stats_daily AS d
WHERE
d.date >= ‘2019-01-01‘
AND d.date <= ‘2021-06-30‘
AND d.series_id IN ( 4974, 11, 22, 33 )
GROUP BY
DATE_FORMAT( d.date, ‘%Y-%m‘ ),
d.series_id
ORDER BY
DATE_FORMAT( d.date, ‘%Y-%m‘ ) DESC
SELECT
DATE_FORMAT( d.date, ‘%Y-%m‘ ) AS 月份,
case when d.series_id = 4974 then sum( d.new_sheng ) else 0 end AS `理想ONE`,
IF
( d.series_id = 11, sum( d.new_sheng ), 0 ) AS `11`,
IF
( d.series_id = 22, sum( d.new_sheng ), 0 ) AS `22`,
IF
( d.series_id = 33, sum( d.new_sheng ), 0 ) AS `33`
FROM
dy_series_stats_daily AS d
WHERE
d.date >= ‘2019-01-01‘
AND d.date <= ‘2021-06-30‘
AND d.series_id IN ( 4974, 11, 22, 33 )
GROUP BY
DATE_FORMAT( d.date, ‘%Y-%m‘ ),
d.series_id
ORDER BY
DATE_FORMAT( d.date, ‘%Y-%m‘ ) DESC