第一种常规方法,利用子查询和集合计算:
select lineCode,
SUM(CASE tmp.alarmSubType WHEN '1' THEN tmp.count ELSE 0 END) '1',
SUM(CASE tmp.alarmSubType WHEN '2' THEN tmp.count ELSE 0 END) '2',
SUM(CASE tmp.alarmSubType WHEN '3' THEN tmp.count ELSE 0 END) '3',
SUM(CASE tmp.alarmSubType WHEN '4' THEN tmp.count ELSE 0 END) '4',
SUM(CASE tmp.alarmSubType WHEN '5' THEN tmp.count ELSE 0 END) '5',
SUM(CASE tmp.alarmSubType WHEN '6' THEN tmp.count ELSE 0 END) '6',
SUM(CASE tmp.alarmSubType WHEN '7' THEN tmp.count ELSE 0 END) '7',
SUM(CASE tmp.alarmSubType WHEN '8' THEN tmp.count ELSE 0 END) '8',
SUM(CASE tmp.alarmSubType WHEN '9' THEN tmp.count ELSE 0 END) '9',
SUM(CASE tmp.alarmSubType WHEN '10' THEN tmp.count ELSE 0 END) '10',
SUM(CASE tmp.alarmSubType WHEN '11' THEN tmp.count ELSE 0 END) '11',
SUM(CASE tmp.alarmSubType WHEN '12' THEN tmp.count ELSE 0 END) '12',
SUM(CASE tmp.alarmSubType WHEN '13' THEN tmp.count ELSE 0 END) '13',
SUM(CASE tmp.alarmSubType WHEN '14' THEN tmp.count ELSE 0 END) '14',
SUM(CASE tmp.alarmSubType WHEN '15' THEN tmp.count ELSE 0 END) '15'
from (
select busstainfo_xl as lineCode, count(*) count, busstainfo_pllx as alarmSubType
from busstainfo
where busstainfo_rq between '20220216' and '20220216'
and busstainfo_bjlx = '疲劳驾驶'
group by busstainfo_xl, busstainfo_pllx
) tmp
GROUP BY lineCode
第二种利用 PIVOT
with tmp as (
select busstainfo_xl as lineCode, count(*) count, busstainfo_pllx as alarmSubType
from busstainfo where busstainfo_rq between '20220216' and '20220216'
and busstainfo_bjlx = '疲劳驾驶'
group by busstainfo_xl, busstainfo_pllx)
SELECT * FROM tmp
PIVOT
(
SUM(count) for [alarmSubType] in ([1])
) TBL
抽时间再做详细解释。
有兴趣参考这两篇行专列文章:
SQL之行转列Pivot函数 - 简书 (jianshu.com)
MySQL行专列、多表联查行专列、sql行专列_李程程的博客-CSDN博客_行专列
示例:
SELECT B.date,B.天然气,B.天然气,B.柴油,B.电
from (
SELECT SUBSTRING(REPLACE(time, '-', ''), 0, 7) date,
type,
sum(amount) AS amount
FROM table
group by SUBSTRING(REPLACE(time, '-', ''), 0, 7), type
) A PIVOT (
SUM(A.amount) FOR [type] IN ([电], [LNG天然气], [CNG天然气],[柴油])
) B
SELECT top 10
SUBSTRING(REPLACE(time, '-', ''), 0, 7) date,
case fill_type when '电' then isnull(sum(amount),0) end 'elec',
case fill_type when 'LNG天然气' then isnull(sum(amount),0) end 'lng',
case fill_type when 'CNG天然气' then isnull(sum(amount),0) end 'cng',
case fill_type when '柴油' then isnull(sum(amount),0) end 'diesel'
FROM table
where SUBSTRING(REPLACE(time, '-', ''), 0, 7) like '202%'
group by SUBSTRING(REPLACE(time, '-', ''), 0, 7), type order by date desc