这些知识常出现在面试题,但是实用价值很高。。其实也就是SQL的高级篇罢了,多用在统计方面,将行数据合并成列数据。希望读者能举一反三,灵活运用。
一个表中的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表
username | sex |
---|---|
wk | 0 |
lj | 1 |
kk | 0 |
请将查询出来的数据按照"lj","wk","kk"排序显示
SELECT * FROM user ORDER BY FIND_IN_SET(username,'lj,wk,kk')
表内容: 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
表中有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
显示格式: 语文 数学 英语 及格 优秀 不及格
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
从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