数据库的一些例子及其分析

来源:互联网 发布:ubuntu开启网络服务 编辑:程序博客网 时间:2024/06/05 05:02

1、表

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

create table #tmp(rq varchar(10),shengfu nchar(1))

insert into #tmp values('2005-05-09','胜')
insert into #tmp values('2005-05-09','胜')
insert into #tmp values('2005-05-09','负')
insert into #tmp values('2005-05-09','负')
insert into #tmp values('2005-05-10','胜')
insert into #tmp values('2005-05-10','负')
insert into #tmp values('2005-05-10','负')

 

分析:其实可以先写这样的sql语句:

       select rq, ( case when shengfu = '胜' then 1 else 0 end)胜,
                      ( case when shengfu ='负' then 1 else 0 end)负
                      from temp
 产生如下的结果:

      rq                胜       负

2005-05-09       1        0

2005-05-09       1        0

2005-05-09       0        1

2005-05-09       0        1

2005-05-10       1        0

2005-05-10       0        1

2005-05-10       0        1

 

然后就group一下就行了!

 

比较好的写法是:

select rq, sum(case when shengfu='胜' then 1 else 0 end)'胜',sum(case when shengfu='负' then 1 else 0 end)'负' from #tmp group by rq

另一种思路:

select a.rq,a.胜,b.负 from
 (select rq,  count(sf) 胜 from temp  where sf='胜' group by rq )a
 inner join
 (select rq, count (sf) 负 from temp where sf='负' group by rq) b
 on a.rq=b.rq

 

2、请用一个sql语句得出结果
从table1,table2中取出如table3所列格式数据,注意提供的数据及结果不准确,只是作为一个格式向大家请教。
如使用存储过程也可以。

table1

月份mon 部门dep 业绩yj
-------------------------------
一月份       01       10
一月份       02       10
一月份       03       5
二月份       02       8
二月份       04       9
三月份       03       8

table2

部门dep       部门名称dname
--------------------------------
       01       国内业务一部
       02       国内业务二部
       03       国内业务三部
       04       国际业务部

table3 (result)

部门dep 一月份       二月份       三月份
--------------------------------------
       01       10         null       null
       02       10         8         null
       03       null       5         8
       04       null       null       9
------------------------------------------

 

思路:这个题实际上只需用到table1 而且table3的答案有点问题

select  dep,sum(case when mon='一月份' then yj else 0 end)一月份,
                  sum(case when mon='二月份' then yj else 0 end)二月份,
                   sum(case when mon='三月份' then yj else 0 end)三月份
  from table1  group by dep order by dep)a ;

结果是:

部门dep 一月份       二月份       三月份
--------------------------------------
       01       10         0        0
       02       10         8        0
       03       5           8        0  
       04       0           9        0
------------------------------------------

然后就把0转为null就行了,其实一开始还是用0来算 这样group就方便了

原创粉丝点击