我正在尝试在MySQL中生成每个月的每月收入(提供商)的报告,我想要的是将月份视为列,将收入视为行。
我已经写了这个查询,但我不知道写些什么来把这几个月作为列:
SELECT T1.provider_id, T2.ad_provider, MONTH(date) AS MONTH, round(SUM(T1.revenue),2) as RevenueTotal
FROM revenue_metrics as T1
LEFT JOIN ad_provider as T2 ON T1.provider_id=T2.id
GROUP BY T1.provider_id, MONTH
ORDER BY MONTH, `RevenueTotal` DESC
答案 0 :(得分:2)
您可以使用CASE ... WHEN
执行此操作:
SELECT T1.provider_id,
T2.ad_provider,
round(SUM(CASE MONTH(date) WHEN 1 THEN T1.revenue END), 2) AS January,
round(SUM(CASE MONTH(date) WHEN 2 THEN T1.revenue END), 2) AS February,
round(SUM(CASE MONTH(date) WHEN 3 THEN T1.revenue END), 2) AS March,
round(SUM(CASE MONTH(date) WHEN 4 THEN T1.revenue END), 2) AS April,
round(SUM(CASE MONTH(date) WHEN 5 THEN T1.revenue END), 2) AS May,
round(SUM(CASE MONTH(date) WHEN 6 THEN T1.revenue END), 2) AS June,
round(SUM(CASE MONTH(date) WHEN 7 THEN T1.revenue END), 2) AS July,
round(SUM(CASE MONTH(date) WHEN 8 THEN T1.revenue END), 2) AS August,
round(SUM(CASE MONTH(date) WHEN 9 THEN T1.revenue END), 2) AS September,
round(SUM(CASE MONTH(date) WHEN 10 THEN T1.revenue END), 2) AS October,
round(SUM(CASE MONTH(date) WHEN 11 THEN T1.revenue END), 2) AS November,
round(SUM(CASE MONTH(date) WHEN 12 THEN T1.revenue END), 2) AS December
FROM revenue_metrics as T1
LEFT JOIN ad_provider as T2 ON T1.provider_id=T2.id
GROUP BY T1.provider_id
但是请注意,现在按月收入排序已经没有意义了,因为竞争收入现在位于不同的列中。
答案 1 :(得分:0)
如果你需要在Numeric Formate中使用月份
SELECT MONTH('2008-02-03');
2
如果你在String Formate中需要月份那么
SELECT MONTHNAME('2008-02-03');
'February'