查看上个月数据
SELECT * FROM table WHERE date_format(time, '%Y %m') = date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y %m')
查询上个月
select date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH), '%m')
– 行转列:方法①
SELECT
id,
name,
GROUP_CONCAT(CASE WHEN subject = ‘语文’ THEN score END SEPARATOR ‘’) ‘语文’,
GROUP_CONCAT(CASE WHEN subject = ‘数学’ THEN score END SEPARATOR ‘’) ‘数学’,
GROUP_CONCAT(CASE WHEN subject = ‘英语’ THEN score END SEPARATOR ‘’) ‘英语’
FROM test1
GROUP BY name;
– 行转列:方法②
SELECT
id,
name,
SUM(IF(subject = ‘语文’,score,0)) AS ‘语文’,
SUM(IF(subject = ‘数学’,score,0)) AS ‘数学’,
SUM(IF(subject = ‘英语’,score,0)) AS ‘英语’
FROM test1
GROUP BY name;
SELECT name,‘语文’ AS subject,语文 AS score FROM test2
UNION ALL
SELECT name,‘数学’ AS subject,数学 AS score FROM test2
UNION ALL
SELECT name,‘英语’ AS subject,英语 AS score FROM test2
ORDER BY name ASC,subject DESC;
总结:
行转列主要借助:CASE WHEN或IF,这两种都是判断条件,思路>当满足某个学科的时候我们把它当做新的一列。
列转行主要借助:UNION或UNION ALL,这两个都是把结果集合并起来,思路> 每次查询学生名称(基本列)和学科的其中一列的值,再把它们组合起来,这样你的结果集就是只有学生名称和科目成绩两列了。(我这里多加了一列科目)