作者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