/* 一个简单的表TABLE 有100条以上的信息,其中包括:
产品 颜色 数量
产品1 红色 123
产品1 蓝色 126
产品2 蓝色 103
产品2 红色 NULL
产品2 红色 89
产品1 红色 203
。。。。。。。。。。。。
请用SQL语句完成以下问题:
1。按产品分类,仅列出各类商品中红色多于蓝色的商品名称及差额数量:
2。按产品分类,将数据按下列方式进行统计显示
产品 红色 蓝色
*/
/*
问题1
方法1
select 产品,
sum(case when 颜色='红色' then 数量 else 0 end)
-sum(case when 颜色='蓝色' then 数量 else 0 end) as 差额
from test
group by 产品
having
sum(case when 颜色='红色' then 数量 else 0 end)
>sum(case when 颜色='蓝色' then 数量 else 0 end)
方法2
select 产品,
sum(case when 颜色='红色' then 数量 when 颜色='蓝色' then -数量 else 0 end)
as 差额
from test
group by 产品
having
sum(case when 颜色='红色' then 数量 when 颜色='蓝色' then -数量 else 0 end)>0
方法3
select 产品,sum(IsNull(数量,0) * Replace(replace(颜色,'红色',1),'蓝色',-1))
from test
group by 产品
having sum(IsNull(数量,0) * Replace(replace(颜色,'红色',1),'蓝色',-1))>0
问题2
方法1
select * from test
select 产品,红色=sum(case when 颜色='红色' then 数量 else 0 end),
蓝色=sum(case when 颜色='蓝色' then 数量 else 0 end) from test group by 产品
方法2
方法3
select 产品,sum(IsNull(数量,0) * Replace(replace(颜色,'红色',1),'蓝色',0))
,sum(IsNull(数量,0) * Replace(replace(颜色,'红色',0),'蓝色',1))
from test
group by 产品
having sum(IsNull(数量,0) * Replace(replace(颜色,'红色',1),'蓝色',-1))>0
*/
sql 面试题总结一
3星 · 超过75%的资源 需积分: 3 167 浏览量
2008-08-24
23:58:01
上传
评论 2
收藏 4KB RAR 举报
grapism
- 粉丝: 2
- 资源: 5