1.如何用一条语句把一张表的数据插入到另一张数据库表中?

Sql代码  

    insert into tableA select * from tableB  

2.如何用一条语句把一张表的数据插入到另一张不存在的数据库表中? 

Sql代码  
  1. select * into tableB from tableA;  
  2. -------或者是下面这种写法  
  3. create table tableB as select * from tableA;  

3.有如下A、B两个表,如何将A表的数据查询出来,结果如B所示?

         A表:

姓名

科目

分数

张三

语文

60

李四

数学

65

张三

英语

70

张三

数学

75

李四

语文

80

李四

英语

68

 

         B表:

姓名

语文

数学

英语

总分

张三

 

 

 

 

李四

 

 

 

 

这里我们用一个t_student表来表示A表,其建表语句如下所示:

Sql代码  

    create table t_student(name varchar2(4), course varchar2(4), score int);  

那么这个时候要用一条SQL语句把A表的数据查询出B表的结果,我们可以如下定义我们的SQL语句:

Sql代码  

select a.name 姓名,sum(case when course='语文' then score end) 语文,sum(cas
e when course='英语' then score end) 英语,sum(case when course='数学' then score
end) 数学,b.total 总分 from t_student a, (select name, sum(score) total from t_
student group by name) b where a.name=b.name group by a.name,b.total order by a.
name desc;

 这条语句的总体思路是:

  • 先用分组的形式查询出每个人的总成绩
  • 用case when的形式把课程列分为多列,这样满足的那一列的成绩就是当前人当前课程的成绩,其他的成绩在当前行为空

姓名       语文       数学       英语

---- ---------- ---------- ----------

张三         60

张三                    75

张三                               70

李四                               68

李四         80

李四                    65

 

  • 把上述两个结果按照相同的姓名连接起来并按照姓名和总分分组,这样我们查询出来的结果就可以显示姓名和总分,那么我们没有按照成绩进行分组,那么当我们用分组语句的时候该如何查询出我们的成绩呢?这个时候sum就起作用了,根据之前分析的,每个人每门成绩只有一个有效值,其他的为空,所以我们对它进行汇总的结果还是其当前课程的成绩,这就可以满足我们在分组的情况下查询出对应的成绩。(在进行分组查询的时候,只能查询出对应的分组字段和统计字段)
  • 最后一步进行排序是为了按照“张三”,“李四”那样的顺序排列

 上面查询出来的结果会如下所示:

姓名       语文       英语       数学       总分

------ ------ ------- ------- --------

张三         60         70         75        205

李四         80         68         65        213

有一个employee表,其结构如下所示:

 

empNo

int

empName

varchar2(20)

age

int

salary

number(7,2)

 

假设这个表的数据量很大,有几千万条数据,请你用一条你觉得最有效率的SQL语句统计出如下四种类型的人数:

  • age>30 and salary>10000
  • age>30 and salary<10000
  • age<30 and salary>10000
  • age<30 and salary<10000

我的思路:

        用case when来进行筛选,用count来进行统计,这样整个数据量只需要统计一遍。 

查询语句: 

select count(case when age>30 and salary>10000 then empNo end) type1,
count(case when age>30 and salary<10000 then empNo end) type2,
count(case when age<30 and salary>10000 then empNo end) type3,
count(case when age<30 and salary<10000 then empNo end) type4 from employee;

 

posted on 2016-05-17 08:44  寻幽径  阅读(139)  评论(0)    收藏  举报