常用SQL查询语句整理笔记【持续更新】

常用SQL查询语句整理笔记

查询表所有数据 SELECT * FROM myTable

查询指定学号学生的信息 SELECT * FROM myTable WHERE studentId=‘001’

IN关键字查询 SELECT name,age,height FROM myTable WHERE studentId in (‘001’,‘002’,‘003’)

LIKE关键词模糊查询 SELECT studentId FROM myTable WHERE name LIKE ‘%明%’

GROUP BY查询 SELECT age FROM myTable GROUP BY age

分组+数量统计 SELECT age,COUNT(1) as num FROM myTable GROUP BY age

HAVING关键字查询 SELECT age,COUNT(1) as num FROM myTable GROUP BY age HAVING num>=2

DISTINCT关键字查询 SELECT DISTINCT age FROM myTable

CASE WHEN 关键字查询 SELECT studentId,age,name CASE WHEN age=10 THEN ‘青年’ WHEN age=20 THEN ‘中年’ WHEN age=‘30’ THEN ‘壮年’ ELSE ‘老年’ END AS ageDesc FROM myTable

嵌套查询 SELECT studentId,age FROM (SELECT studentId,age,name CASE WHEN age=10 THEN ‘青年’ WHEN age=20 THEN ‘中年’ WHEN age=‘30’ THEN ‘壮年’ ELSE ‘老年’ END AS ageDesc FROM myTable) t

更新 UPDATE myTable set age=‘11’ WHERE studentId=‘001’

删除 DELETE FROM myTable WHERE studentId=‘002’

内连接 SELECT A.studentId,A.age,A.name FROM myTable A INNER JOIN otherTable B ON A.studentId=B.id

左连接 SELECT A.studentId,A.age,A.name FROM myTable A LEFT JOIN otherTable B ON A.studentId=B.id

右连接 SELECT A.studentId,A.age,A.name FROM myTable A RIGHT JOIN otherTable B ON A.studentId=B.id

多表连接 SELECT A.studentId,A.age,A.name FROM myTable A INNER JOIN otherTable B ON A.studentId=B.id INNER JOIN hisTable C ON B.id=C.primaryId

UNION合并【会自动去除重复行】 SELECT studentId,age,name FROM myTable UNION SELECT id,age,name FROM otherTable

UNION ALL合并【不会自动去除重复行】 SELECT studentId,age,name FROM myTable UNION ALL SELECT id,age,name FROM otherTable

ROW_NUMBER()【为分组内的每一行返回一个行号】 SELECT studentId,age,name,height,row_number() OVER(PARTITION BY age order by height) AS rowId FROM myTable

SUM() OVER()【实现GROUP BY效果】 SELECT studentId,age,name,height,SUM(height) OVER(PARTITION BY age) AS avg FROM myTable

窗口函数 SELECT studentId,age,name,height,SUM(height) OVER (ORDER BY studentId ROWS BETWEEN UNBOUNDED PRECEDING AND CURREND ROW) AS total FROM myTable

移动窗口 SELECT studentId,age,name,height,SUM(height) OVER (ORDER BY studentId ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS total,SUM(height) OVER (ORDER BY studentId ROWS BETWEEN 3 PRECEDING AND CURRENT ROW) AS total2 FROM myTable

行转列 SELECT * FROM myTable PIVOT (SUM(score) FOR subject IN (语文, 数学, 英语))

列转行 SELECT * FROM myTable UNPIVOT (score FOR subject IN (“语文”,“数学)”,“英语”))

你可能感兴趣的:(数据库,大数据,编程技术)