SQL高级运用

这些知识常出现在面试题,但是实用价值很高。。其实也就是SQL的高级篇罢了,多用在统计方面,将行数据合并成列数据。希望读者能举一反三,灵活运用。

读取数据库中的重复记录 (group by & having)

一个表中的Id有多条重复记录,所有重复的id读取出来。

select id, COUNT(*) as count from tb GROUP BY id HAVING count>1

字符串替换操作

将manhua_name字段里所有的“漫画街”替换为“wangking717”

UPDATE table1 SET manhua_name = REPLACE(manhua_name,"漫画街","wangking717");

指定字符串排序

users表

usernamesex
wk0
lj1
kk0

请将查询出来的数据按照"lj","wk","kk"排序显示

SELECT * FROM user ORDER BY FIND_IN_SET(username,'lj,wk,kk')

一道SQL语句面试题,关于group by

表内容:
2005-05-09 胜
2005-05-09 胜
2005-05-09 负
2005-05-09 负
2005-05-10 胜
2005-05-10 负
2005-05-10 负

如果要生成下列结果, 该如何写sql语句?

胜 负
2005-05-09 2 2
2005-05-10 1 2

select time, sum(case when shengfu='胜' then 1 else 0 end) as '胜',sum(case when shengfu='负' then 1 else 0 end) as '负' from my_table group by time

请教一个面试中遇到的SQL语句的查询问题

表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列。

select (case when a>b then a else b end ),(case when b>c then b esle c end) from my_table

有一张表,里面有3个字段:语文,数学,英语。其中有3条记录分别表示语文70分,数学80分,英语58分,请用一条sql语句查询出这三条记录并按以下条件显示出来(并写出您的思路):大于或等于80表示优秀,大于或等于60表示及格,小于60分表示不及格。

显示格式:
语文 数学 英语
及格 优秀 不及格

select
(case when 语文>=80 then '优秀'
when 语文>=60 then '及格'
else '不及格') as 语文,
(case when 数学>=80 then '优秀'
when 数学>=60 then '及格'
else '不及格') as 数学,
(case when 英语>=80 then '优秀'
when 英语>=60 then '及格'
else '不及格') as 英语,
from my_table

请用一个sql语句得出结果

从table1,table2中取出如Result所列格式数据,注意提供的数据及结果不准确,只是作为一个格式向大家请教。
如使用存储过程也可以。


table1
月份mon 部门dep 业绩yj
一月份 01 10
一月份 02 10
一月份 03 5
二月份 02 8
二月份 04 9
三月份 03 8


table2
部门dep 部门名称dname
01 国内业务一部
02 国内业务二部
03 国内业务三部
04 国际业务部


Result
部门名称dname 一月份 二月份 三月份
国内业务一部 10 null null
国内业务二部 10 8 null
国内业务二部 null 5 8
国际业务部 null null 9


select a.dep,
sum(case when a.mon=1 then a.yj else 0 end) as '一月份',
sum(case when a.mon=2 then a.yj else 0 end) as '二月份',
sum(case when a.mon=3 then a.yj else 0 end) as '三月份'
from table2 b left join table1 a on a.dep=b.dep

原文地址:https://www.cnblogs.com/lxwphp/p/15452930.html