1、关于group by表内容:
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 A(rq varchar(10),shengfu nchar(1));
insert into A values(‘2005-05-09’,‘胜’);
insert into A values(‘2005-05-09’,‘胜’);
insert into A values(‘2005-05-09’,‘负’);
insert into A values(‘2005-05-09’,‘负’);
insert into A values(‘2005-05-10’,‘胜’);
insert into A values(‘2005-05-10’,‘负’);
insert into A values(‘2005-05-10’,‘负’);
方法一:利用子查询
select a.rq 日期,a.cn 胜,b.cn 负 from
(select rq,count(shengfu) cn from A where shengfu=‘胜’ group by rq) a,
(select rq,count(shengfu) cn from A where shengfu=‘负’ group by rq) b
where a.rq=b.rq
方法二:高级查询—使用case表达式
case表达式可以在sql中实现if-then-else型的逻辑,而不用去使用PL/SQL。case工作方式与decode类似,但是我们应该使用case,因为它与ansi兼容。
有两种类型的case表达式
a 简单case表达式,使用case表达式确定返回值
b 搜索case表达式,使用条件确定返回值
select rq,sum(case when shengfu=‘胜’ then 1 else 0 end) as 胜,
sum(case when shengfu=‘负’ then 1 else 0 end) as 负
from tmp
group by rq
方法三:通过表的内连接与子查询联合实现,可以说是另一种方式,思想类似于方法一。
select a.rq,a.胜,b.负 from
(select rq,count(shengfu) 胜 from tmp where shengfu='胜’group by rq) a inner join
(select rq,count(shengfu) 负 from tmp where shengfu='负’group by rq) b
on a.rq=b.rq
2.表中有A B C三列,用SQL语句实现:
当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列。
create table tmp2(a int,b int ,