利用sql语句实现的几个功能

1、SQL 语句中,union的使用:
   Table a:    field1,field2             Table b:   field1,field2
   data:       1       2                 data:      2,     2  
               1       4                            2,     3
   sql:  select filed1 from a union select field1 from b
   data: field1
         1
         2
   sql:  select filed1,field2 from a union select field1,field2 from b
   data: field1,field2
         1      2
         1      4
         2      2
         2      3 
2、table1{id:int,charge:int,fk:int}
   table2{id:int,charge:int}
   修改table2,使charge等于table1中相应值的和
   sql:update a set a.charge=b.totalcharge
        from (select id,sum(charge) totalcharge from table1 group by id)  b,table2 a
        where a.id=b.id
3、出发点   目的地     路程
      A         B
      A         C
      A         D
      A         E
      B         F
      C         G
      C         A
      用sql语句计算出所有从A出发所能到达的目的地,包括间接的。
   sql:select distinic 目的地 from 表
        where 出发点 in (
                        select distinic 目的地 from  表
                        where 出发点='A' union select 'A')
   说明:上面的方法只使用一级嵌套。可以满足此题的需求。
4、表t1
     year   quarter   num
     2001     1        3.4
     2001     2        5.12
     2001     3        6.13
     2001     4        8.14
     2002     1        5.21
     2002     2        4.22
     2002     3        6.23
     2002     4        4.24
     用sql语句获取下面的数据
     2001  3.4  5.12  6.13  8.14
     2002  5.21  4.22  6.23  4.24

   sql:select [year],avg(case[quarter] when '1' then num) as 'quarter1',
               avg(case[quarter] when '2' then num) as 'quarter2',
               avg(case[quarter] when '3' then num) as 'quarter3',
               avg(case[quarter] when '4' then num) as 'quarter4'
        from t1 group by year

转载于:https://www.cnblogs.com/swingboat/archive/2005/02/20/106511.html

猜你喜欢

转载自blog.csdn.net/weixin_34334744/article/details/93957302