数据库分组求和问题
2012-03-23 14:34
295 查看
表包含三列,[id] ,[countNo],[type],id 表示仓库编号,countno表示货物数量,[type]表示货物类型
现在要求统计每个仓库各个货物的数量,包含四列仓库编号,货物1的数量,货物2的数量,货物3的数量..货物N的数量。
1 第一种方法,使用inner join和as给表取别名,语句如下:
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的另外一种写法
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方法,语句如下
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
这两种方式其实都是假定货物种类是确定的,如何货物种类不确定,或者经常变动,如何操作?就需要借助于游标或者临时表之类的复杂语句了。
现在要求统计每个仓库各个货物的数量,包含四列仓库编号,货物1的数量,货物2的数量,货物3的数量..货物N的数量。
1 第一种方法,使用inner join和as给表取别名,语句如下:
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的另外一种写法
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方法,语句如下
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
这两种方式其实都是假定货物种类是确定的,如何货物种类不确定,或者经常变动,如何操作?就需要借助于游标或者临时表之类的复杂语句了。
相关文章推荐
- 解决问题之道--使用Java实现数据的分组求和
- 数据库分组查询最大值的问题
- 数据库查询分组类型问题总结
- 多用户分组权限管理问题的数据库设计
- 数据库 分组统计问题
- 数据库求和统计问题
- hibernate操作数据库遇到问题的时候检查主键生成策略
- pid及socket文件丢失,数据库无法启动问题
- 数据库的分批查询问题
- 关于exp导出oracle11g的数据库问题 提示exp-00028这个错误
- 数据库存储过程变量问题
- 安装msdn后 数据库或者vs加载插件报错问题
- TFS - Analysis 数据库问题
- 解决还原数据库产生的孤立用户问题
- 数据库并发事务中的问题与解决方案
- mybatis插入数据库时的问题记录
- NYOJ 508 余数求和 (数论问题)
- 【mysql】新方法修改数据库密码以及解决--ERROR 1045 (28000)的问题
- oracle 数据库的简单小问题
- 数据库问题集合