SQL Server查询以获取每行的总计

时间:2017-07-18 11:37:00

标签: sql sql-server tsql ssms-2014

我有两张表InvoiceLineDiscount

enter image description here

我需要获得一个结果集,其中包含发票行项目以及折扣表中折扣的总数(SUM),如下所示:

enter image description here

如何只使用一个查询来实现这一目标?

4 个答案:

答案 0 :(得分:1)

DECLARE @InvoiceLine TABLE
    (
      InvoiceHeaderID INT ,
      InvoiceLineNo INT ,
      ProductCode VARCHAR(5) ,
      Price MONEY
    );

INSERT  INTO @InvoiceLine
VALUES  ( 1, 1, 'AB001', 1200 ),
        ( 2, 1, 'AC002', 1525 );


DECLARE @Discount TABLE
    (
      InvoiceHeaderID INT ,
      InvoiceLineNo INT ,
      DiscountCategory VARCHAR(10) ,
      discountValue MONEY
    );
INSERT  INTO @Discount
VALUES  ( 1, 1, 'SalesDisc', 120 ),
        ( 1, 1, 'FixedOffer', 100 ),
        ( 2, 1, 'SalesDisc', 152.50 );


SELECT  l.InvoiceHeaderID ,
        l.InvoiceLineNo ,
        l.ProductCode ,
        l.Price ,
        ISNULL(SUM(d.discountValue),0) [TotalDiscount]
FROM    @InvoiceLine l
        LEFT JOIN @Discount d ON d.InvoiceHeaderID = l.InvoiceHeaderID
                                 AND d.InvoiceLineNo = l.InvoiceLineNo
GROUP BY l.InvoiceHeaderID ,
        l.InvoiceLineNo ,
        l.ProductCode ,
        l.Price; 

结果

enter image description here

答案 1 :(得分:0)

SELECT
A.InvoiceHeaderID, A.InvoiceLineNo, ProductCode, Price, SUM(DiscountValue) as TotDiscount
FROM
InvoiceLine A, Discount B
WHERE
A.InvoiceHeaderID = B.InvoiceHeaderID
AND A.InvoiceLineNo = B.InvoiceLineNo
GROUP BY
A.InvoiceHeaderID, A.InvoiceLineNo, ProductCode, Price
Order BY
A.InvoiceHeaderID, A.InvoiceLineNo

答案 2 :(得分:0)

SavePicture picturebox2.picture, "filename.bmp"

答案 3 :(得分:0)

SELECT
InvoiceLine .InvoiceHeaderID, InvoiceLine .InvoiceLineNo, ProductCode, Price, SUM(DiscountValue) as TotDiscount
FROM
InvoiceLine, Discount 
WHERE
InvoiceLine .InvoiceHeaderID = Discount .InvoiceHeaderID AND A.InvoiceLineNo = Discount .InvoiceLineNo
GROUP BY InvoiceLine .InvoiceHeaderID, InvoiceLine .InvoiceLineNo, ProductCode, Price
Order BY InvoiceLine .InvoiceHeaderID, InvoiceLine .InvoiceLineNo