我有下表,其中包含以下属性:
vendor_invoicedetails
Venid(Pk)
ven_inv_ref(Fk)
Item_Code
Item_Name
UnitPrice
VenQuantity
我想将unitPrice
与VenQuantity
相乘得到我用以下查询做的总价
select item_code,
VEN_INV_REF,
unitprice * ven_itemquantity as total
from vendor_invoicedetails;
我想要的是将TotalPrice
总和为两个相同Ven_inv_Ref(Fk)
列的总和。
在上图中,我想要对那些具有相同VEN_INV_REF
个数字的条目求和。
答案 0 :(得分:4)
试试这个:
DECLARE @datatable TABLE
(
ITEM_CODE NVARCHAR(32) PRIMARY KEY CLUSTERED,
ven_inv_ref NVARCHAR(50),
Item_Name NVARCHAR(50),
UnitPrice FLOAT,
VenQuantity INT
)
INSERT INTO @datatable
(ITEM_CODE, ven_inv_ref, UnitPrice, VenQuantity)
VALUES ('battery', 15, 100, 4)
INSERT INTO @datatable
(ITEM_CODE, ven_inv_ref, UnitPrice, VenQuantity)
VALUES ('ABCDE', 16, 200, 4)
INSERT INTO @datatable
(ITEM_CODE, ven_inv_ref, UnitPrice, VenQuantity)
VALUES ('A4', 16, 400, 4)
-- whats in the table
SELECT *
FROM @datatable
-- group by reference
SELECT
ven_inv_ref,
SUM(UnitPrice*VenQuantity) AS totalvalue
FROM @datatable
GROUP BY ven_inv_ref
结果