51代码网ORACLEMYSQLSQL SERVER其它数据库java/jspasp/asp.netC/C++/VC++APP应用其它语言服务器应用
您现在的位置: 51代码网 >> 其它数据库 >> 文章正文

db2区间分组的问题

更新时间:2012-3-11:  来源:51代码网

表是这样的 销量表 id是编码 price 是单价 quantity 是数量 totalprice是总价

id price quantity totalprice
1 100 1 100
1 100 2 200
2 200 1 200
3 400 1 400
3 400 2 800
4 600 1 600
5 700 2 1400

现在想做一张这样的查询
价格区间 销售金额 销量  
0-300
301-600
601以上

请问这样的查询SQL该如何写呢
select '0-300' as 价格带, sum(totalprice) as 销售金额 from 表 where price<=300
union all select '301-600' as 价格带, sum(totalprice) as 销售金额 from 表 where price BETWEEN 301 AND 600
union all select '601以上' as 价格带, sum(totalprice) as 销售金额 from 表 where price>=601

SELECT '0-300',SUM(CASE WHEN price<=300 THEN quantity ELSE 0 END),
SUM(CASE WHEN price<=300 THEN totalprice ELSE 0 END) FROM TT
UNION

SELECT '301-600',SUM(CASE WHEN price BETWEEN 301 AND 600 THEN quantity ELSE 0 END),
SUM(CASE WHEN price BETWEEN 301 AND 600 THEN totalprice ELSE 0 END) FROM TT
UNION

SELECT '601以上',SUM(CASE WHEN price>=601 THEN quantity ELSE 0 END),
SUM(CASE WHEN price>=601 THEN totalprice ELSE 0 END) FROM TT
UNION

  • 上一篇文章:
  • 下一篇文章: 没有了
  • 赞助商链接
    推荐文章
  • 此栏目下没有推荐文章
  • {
    设为首页 | 加入收藏 | 友情链接 | 网站地图 | 联系站长 |