我有一个看起来像这样的表:
[invoice_lines]
id(int),customerid(int),price(int),productname(text)
我想查询此表,并提取所有行。但我也想用customerid = customerid提取所有行的平均价格。
所以我想说我有一行有这些值:
id(1),customerid(134),price(125),productname(Internet)
我想提取该行,但我还想要一个列,其中包含具有customerid 134的所有行的平均价格。
任何指针? :)
答案 0 :(得分:2)
SELECT id, customerid, price, productname,
AVG(price) OVER (PARTITION BY customerid) AS avg_price
from invoice_lines
答案 1 :(得分:1)
DECLARE @id INT
SET @id = 1
SELECT id,
customerid,
price,
productname,
(
SELECT AVG(price)
FROM invoice_lines i
WHERE i.customerid = o.customerid
)AS avgprice
FROM invoice_lines o
WHERE o.id = @id