码迷,mamicode.com
首页 > 数据库 > 详细

sql语句

时间:2015-04-19 22:39:54      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

1. 关于group by
 
  日期     结果
2005-05-09   胜
2005-05-09   胜
2005-05-09   负
2005-05-09   负
2005-05-10   胜
2005-05-10   负
2005-05-10   负
  
  日期    胜  负
2005-05-09   2   2
2005-05-10   1   2
 
select 日期,sum(case when 结果=‘胜‘ then 1 else 0 end),sum(case when 结果=‘负‘ then 1 else 0 end) from table  group by 日期;
 
2. 关于case
 
  a). 表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列。
  select case(when A>B the A else B end), case(when B>C then B else C) from table;
 
  b). 请取出tb_send表中日期(SendTime字段)为当天的所有记录?(SendTime字段为datetime型,包含日期与时间);
  select * from table where datediff(dd, SendTime, getdata())=0;
 
  c). 有一张表,里面有3个字段:语文,数学,英语。其中有3条记录分别表示语文70分,数学80分,英语58分,
  记录并按以下条件显示:大于或等于80表示优秀,大于或等于60表示及格,小于60分表示不及格。
 
  语文 数学 英语
  及格 优秀 不及格
 
  select case(when 语文>=80 then ‘优秀‘ when 语文>=60 then ‘及格‘ else ‘不及格‘) as ‘语文‘,  .... from table;
 
3. 关于distinct(去重)
  查询出每门课都大于80分的学生姓名 

  name   kecheng   fenshu
  张三     语文       81
  张三     数学       75
  李四     语文       76
  李四     数学       90
  王五     语文       81
  王五     数学       100
  王五     英语       90


  select name from table where name not in (select distinct name from table where fenshu<=80);

 
4. left join, right join, inner join区别
  left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录:右表记录不足的地方均为NULL;
  right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录:左表记录不足的地方均为NULL;
  inner join(等值连接) 只返回两个表中联结字段相等的行。
 
5.count
  select count(distinct store) from table;
 
6. top
  select top 2 * from table;       (头2条数据)
  slect top 50 PERCENT * from table;    (50%的数据)
 
7. order by(排序)
  select company from table order by company DESC(降序)/ASC(默认升序);
 
8. CREATE INDEX(创建索引)
  CREATE_INDEX personIndex ON table(LastName DESC, FirstName);
 
 9. AVG(平均值)
  select AVG(index) as avg_index from table;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

sql语句

标签:

原文地址:http://www.cnblogs.com/hj-blog/p/4440162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!