查詢表某列的加權平均值

2021-08-31 02:42:06 字數 2621 閱讀 9775

以乙個簡單商品表為例,商品表包含商品編號,批次,數量,**等字段,現在想要查詢不同批次商品的加權平均價,具體問題描述如下:

建表語句(展開-複製-執行即可初始化資料):

create table [dbo].[product]( [id] [int] null, --商品編號 [productid] [int] null, --商品id [batchnumber] [nchar](50) null, --商品批次 [price] [decimal](18, 2) null, --商品** [amount] [int] null --商品數量 ) insert into product (id,productid,batchnumber,price,amount)values (1,1,'000001','5.00','5') --商品1 批次1 insert into product (id,productid,batchnumber,price,amount)values (2,3,'000004','5.00','2') insert into product (id,productid,batchnumber,price,amount)values (3,5,'000001','5.00','2') insert into product (id,productid,batchnumber,price,amount)values (4,1,'000003','8.00','7') --商品1 批次2 insert into product (id,productid,batchnumber,price,amount)values (5,7,'000001','5.00','2') insert into product (id,productid,batchnumber,price,amount)values (6,1,'000005','7.00','3') --商品1 批次3

表資料如下:

每個商品有不同的批次,每個批次又有不同的** ,如下圖所示:

現在要實現的查詢是:根據商品id,查詢出該商品的所有批次及數量,以及加權平均**;

查詢顯示結果如下:

分析過程:

1.銷售總量字段容易被查出了,乙個sum語句就夠了,難點在於將批次(字串)求和。

解決思路:專門寫乙個自定義函式來獲取批次及數量的疊加內容:

create function getstring

(@id int)

returns nvarchar(500) as

begin

declare @all nvarchar(500)

set @all=''

select @all=@all+p.batchnumber+'('+cast(sum(p.amount)as char(100))+')'+','

from product as p where productid=@id

group by p.batchnumber

return @all

end2.考慮加權平均價的計算,這裡可以用臨時表的方法實現。

第一步:增加乙個計算列,總價-total

select *,price*amount astotalfrom product where productid=1

第二步:查詢出加權平均價

selectsum(total)/sum(amount)from(select *,price*amount as total from product where productid=1)temp

第三步:將查詢語句集中起來得到查詢結果

select replace(dbo.getstring(p.productid),' ','')as '批次及數量',

sum(p.amount)as '總銷售量',

(select sum(total)/sum(amount)from(select *,price*amount as total from product where productid=1)temp)as '加權平均價'

from product as p

where productid=1

group by productid

注: replace函式用來除去查詢結果中的空字元。

小結:執行下面**,即可查詢結果。

select replace(dbo.getstring (p.productid),' ','')as '批次及數量',

sum(p.amount)as '總銷售量',

(select sum(total)/sum(amount)from(select *,price*amount as total from product where productid=1)temp)as '加權平均價'

from product as p

where productid=1

group by productid

加權平均值

加權平均數與算術平均數類似,不同點在於,資料中的每個點對於平均數的貢獻並不是相等的,有些點要比其他的點更加重要。加權平均數的概念在描述統計學中具有重要的意義,並且在其他數學領域產生了更一般的形式。如果所有的權重相同且等於一,那麼加權平均數與算術平均數相同。加權平均數作為算術平均數的更廣義的表現形式,...

求每行每列的平均值和總和

需求 求分數的平均值和總和 1 匯入包 import pandas as pd s pd.read excel r d pythonproject pandas玩轉excel r 源 019 students.xlsx index col id 2 擇需要計算的列 temp s test 1 tes...

生信(五)awk求取某一列的平均值

awk是生信人必須要掌握的命令列工具。為啥?因為它太強大了。我們舉乙個例子來說明。假設我們有乙個1000萬行的檔案,大概長這樣 怎麼求第四列的平均數呢?python版本 我們可以用幾行python 解決,比如這樣 r版本 用r來做計算也是很適合的,比如像這樣 awk版本 awk用一行 就可以解決問題...