作者pttsasho (sasho)
看板Database
标题Re: [SQL ] 如何暂存查询结果作为後续的参数使用
时间Tue Sep 17 12:48:35 2013
※ 引述《pttsasho (sasho)》之铭言:
假设有以下Table
Customer Amount
-----------------------
A 10
B 20
C 30
如果我想计算A、B、C三个客户
分别占本公司销售比重的话,必须先计算出总销售数量 (60)
然後再分别将个别客户的销售数量除以总数量
想请教各位前辈,是否有办法利用SQL语法一次完成呢?
感谢
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.171.210.3
1F:→ fantasyj:select sum(amount) as a, avg(amount) as b from table 09/15 08:54
2F:→ pttsasho:这样求出来的应该是平均值吧! 我想查询的是各别客户的 09/15 09:26
3F:→ pttsasho:比重。比方说A客户比重为:10/60 = 0.167 这样,谢谢! 09/15 09:27
4F:→ fantasyj:select a.customer, a.amount, a.amount / b.toal_amt 09/15 18:33
5F:→ fantasyj: from table as a, 09/15 18:34
6F:→ fantasyj: (select sum(b.amount) as total_amt 09/15 18:34
7F:→ fantasyj: from table as b) as b 09/15 18:34
感谢F大的指点 受教了
另外这边还有个问题 假设我的表格如下:
Customer Amount
-----------------------
A 10
A 11
A 12
B 20
B 21
B 22
C 30
同样是希望能够算出个别客户的比重
但不知为什麽我的叙述查询出来的结果不太对 是否可请各位前辈帮忙看一下
select a.customer,sum(a.amount),sum(a.amount)/b.total
from table as a, (select sum(b.amount) as total_amt from table as b) as b
group by a.customer
不知道为什麽 sum(a.amount)出来的结果与实际数值不符
还请各位前辈帮忙
感谢
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.171.212.181
※ 编辑: pttsasho 来自: 118.171.212.181 (09/17 12:49)
※ 编辑: pttsasho 来自: 118.171.212.181 (09/17 12:51)
8F:推 fantasyj:select a.customer, a.amt, a.amt/b.total_amt 09/17 14:30
9F:推 fantasyj:from (select a.customer,sum(a.amount) as amt from tab 09/17 14:32
10F:→ fantasyj:le as a group by a.customer) as a, 09/17 14:33
11F:→ fantasyj:(select sum(b.amount) as total_amt from table as b) 09/17 14:34
12F:→ fantasyj:上面的拼起来执行看看(用手机不太好回文) 09/17 14:35