查询添加相同的列条目W.R.T其外键

时间:2012-11-30 07:43:30

标签: sql oracle11g

我有下表,其中包含以下属性:

vendor_invoicedetails
   Venid(Pk)
   ven_inv_ref(Fk)
   Item_Code
   Item_Name
   UnitPrice
   VenQuantity
  1. 我想将unitPriceVenQuantity相乘得到我用以下查询做的总价

    select item_code, 
           VEN_INV_REF, 
           unitprice * ven_itemquantity as total
      from vendor_invoicedetails;
    
  2. 我想要的是将TotalPrice总和为两个相同Ven_inv_Ref(Fk)列的总和。

  3. enter image description here

    在上图中,我想要对那些具有相同VEN_INV_REF个数字的条目求和。

1 个答案:

答案 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

结果

enter image description here