数据库分组求和语句

来源:未知 责任编辑:责任编辑 发表时间:2013-12-22 14:56 点击:
 
表包含三列,[id]   ,[countNo],[type],id 表示仓库编号,countno表示货物数量,[type]表示货物类型
 
现在要求统计每个仓库各个货物的数量,包含四列仓库编号,货物1的数量,货物2的数量,货物3的数量..货物N的数量。
 
1 第一种方法,使用inner join和as给表取别名,语句如下:
 
[sql]
select a.id ,sum(a.countno) countno1,sum(b.countno) countno2 ,sum(c.countno)  countno3  
from [Table_1] as a   
inner join [Table_1] as b on a.id=b.id  
inner join [Table_1] as c on a.id=c.id  
where a.type=1 and b.type=2.and c.type=3   
group by a.id  
 或者是iner join的另外一种写法
 
[sql]
select a.id ,sum(a.countno),sum(b.countno),sum(c.countno)   
from [Table_1] as a ,  
 [Table_1] as b   
,[Table_1] as c  
where a.type=1 and b.type=2 and c.type=3 and a.id=b.id and a.id=c.id  
group by a.id,a.type  
 
2使用case when方法,语句如下
 
[sql]
select a.id ,  
sum(case  when type=1 then countno else 0 end),  
sum(case  when type=2 then countno else 0 end),  
sum(case  when type=3 then countno else 0 end)  
from [Table_1] as a group by a.id  
 
这两种方式其实都是假定货物种类是确定的,如何货物种类不确定,或者经常变动,如何操作?就需要借助于游标或者临时表之类的复杂语句了。
 
 
 
摘自 xuexiaodong2009的专栏
    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • Request.ServerVariables 参数大全
    • 执行全文索引时出现权限不足的解决方法
    • 导入excel文件处理流程节点的解决方案
    • 查看sql修改痕迹(SQL Change Tracking on Table)
    • App数据层设计及云存储使用指南
    • PostgreSQL启动过程中的那些事三:加载GUC参数
    • MongoDB安装为Windows服务方法与注意事项
    • Percolator与分布式事务思考(二)
    • 写给MongoDB开发者的50条建议Tip1
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1