经典sql语句汇总

1,某条数据放首位,其他倒序并分页

  select * from student order by(

    case
         when id='2'  then 1

    ELSE 4

    END),id desc limit 0,5;

2,给查询的每条记录添加编号

  select (@i:=@i+1) no , s.* from student s , (select @i:=0) as i

3,数据存在则修改,不存在则添加

  replace into student(id,name,age,sex) values(

    select s.id from student s where s.name='张三' limit 1),'张三','18',‘男’);

4,创建副表,并备份表数据

  DROP TABLE IF EXISTS 'student_bak';

  create table student_bak like student;

  insert into student_bak select * from student;

5,根据t表的时间,实现左右表的全连接,并格式化时间,空数据替换

  select t.ID,t.TRANSACT_TIME,ifnull(T1.RMB_MONRY,'0.00'),ifnull(T1.RMB_NUM,'0'),ifnull(T2.MY_MONRY,'0.00'),ifnull(T2.MY_NUM,'0') from(

   select (@i:=@i+1) ID,DATE_FROMAT(tansact_time,'%Y-%m-%d')TRANSACT_TIME from bank_stages_transact,(select @i:=0) as i

      where status = '0'  group by DATE_FROMAT(transact_time,'%Y-%m-%d') desc) t

   left join

    (select DATE_FROMAT(tansact_time,'%Y-%m-%d')TRANSACT_TIME,SUM(transact_monry)RMB_MONEY,COUNT(1)RMB_NUM from bank_stages_transact

      where status = '0' and  currency_name = '人民币'  group by DATE_FROMAT(transact_time,'%Y-%m-%d') desc) t1

     on  t.transact_time = t1.transact_time  

     left join

    (select DATE_FROMAT(tansact_time,'%Y-%m-%d')TRANSACT_TIME,SUM(transact_monry)MY_MONEY,COUNT(1)MY_NUM from bank_stages_transact

      where status = '0' and currency_name = '美元'  group by DATE_FROMAT(transact_time,'%Y-%m-%d') desc) t2

     on  t.transact_time = t2.transact_time

  )

6,统计不同年龄的总人数及男女生各有多少人

  select age,GROUP_CONCAT(sex)sex,count(1)  from student group by age desc

 

你可能感兴趣的:(经典sql语句汇总)