可以拿一点真实结构,或者相似的表模型贴出来。
SELECT company_key,
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 0 THEN sum ELSE 0 END) AS '第1天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 1 THEN sum ELSE 0 END) AS '往前第2天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 2 THEN sum ELSE 0 END) AS '往前第3天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 3 THEN sum ELSE 0 END) AS '往前第4天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 4 THEN sum ELSE 0 END) AS '往前第5天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 5 THEN sum ELSE 0 END) AS '往前第6天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 6 THEN sum ELSE 0 END) AS '往前第7天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 7 THEN sum ELSE 0 END) AS '往前第8天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 8 THEN sum ELSE 0 END) AS '往前第9天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 9 THEN sum ELSE 0 END) AS '往前第10天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 10 THEN sum ELSE 0 END) AS '往前第11天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 11 THEN sum ELSE 0 END) AS '往前第12天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 12 THEN sum ELSE 0 END) AS '往前第13天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 13 THEN sum ELSE 0 END) AS '往前第14天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 14 THEN sum ELSE 0 END) AS '往前第15天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 15 THEN sum ELSE 0 END) AS '往前第16天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 16 THEN sum ELSE 0 END) AS '往前第17天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 17 THEN sum ELSE 0 END) AS '往前第18天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 18 THEN sum ELSE 0 END) AS '往前第19天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 19 THEN sum ELSE 0 END) AS '往前第20天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 20 THEN sum ELSE 0 END) AS '往前第21天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 21 THEN sum ELSE 0 END) AS '往前第22天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 22 THEN sum ELSE 0 END) AS '往前第23天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 23 THEN sum ELSE 0 END) AS '往前第24天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 24 THEN sum ELSE 0 END) AS '往前第25天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 25 THEN sum ELSE 0 END) AS '往前第26天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 26 THEN sum ELSE 0 END) AS '往前第27天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 27 THEN sum ELSE 0 END) AS '往前第28天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 28 THEN sum ELSE 0 END) AS '往前第29天',
SUM(CASE WHEN TO_DAYS(NOW() )-TO_DAYS(action_date) = 29 THEN sum ELSE 0 END) AS '往前第30天'
FROM t
WHERE company_key = '';-- 这里用登陆人的公司key