试试这个:
SELECT
agency_id,
SUM(IF(month = 1, numRecords, NULL)) AS 'January',
SUM(IF(month = 2, numRecords, NULL)) AS 'Feburary',
SUM(IF(month = 3, numRecords, NULL)) AS 'March',
SUM(IF(month = 4, numRecords, NULL)) AS 'April',
SUM(IF(month = 5, numRecords, NULL)) AS 'May',
SUM(IF(month = 6, numRecords, NULL)) AS 'June',
SUM(IF(month = 7, numRecords, NULL)) AS 'July',
SUM(IF(month = 8, numRecords, NULL)) AS 'August',
SUM(IF(month = 9, numRecords, NULL)) AS 'September',
SUM(IF(month = 10, numRecords, NULL)) AS 'October',
SUM(IF(month = 11, numRecords, NULL)) AS 'November',
SUM(IF(month = 12, numRecords, NULL)) AS 'December',
SUM(numRecords) AS total
FROM (
SELECT agency_id, month(departure_date) AS month, count(*) as numRecords
FROM your_table_name
GROUP BY agency_id, month
) AS SubTable1 GROUP BY agency_id
对于特定机构 ID 不存在记录的月份,此查询将显示null
。如果要将其显示为0
,请更新查询并将 替换NULL
为文字0
。