How to separate a record to get the amount

后端 未结 2 1450
刺人心
刺人心 2021-02-11 09:50

I got total 160 Quantity in the Stock.

How to get first 100 quantity total amount and last 60 quantity total amount?

The table is sort by Date and Stock ID.

2条回答
  •  情歌与酒
    2021-02-11 10:30

    Try this:

    Result A:

    SELECT A.ProductID AS 'Product ID', '100' AS 'Quantity', SUM(A.Amount) as 'Total Amount'
    FROM tblStock A
    WHERE StockID IN (SELECT B.StockID from tblStock B ORDER BY B.StockID ASC LIMIT 100)
    

    Result B:

    SELECT A.ProductID AS 'Product ID', '60' AS 'Quantity', SUM(A.Amount) as 'Total Amount'
    FROM tblStock A
    WHERE StockID IN (SELECT B.StockID from tblStock B ORDER BY B.StockID DESC LIMIT 60)
    

    Instead of using IN, you can use JOIN.

    Result A:

    SELECT A.ProductID AS 'Product ID', '100' AS 'Quantity', SUM(A.Amount) AS 'Total Amount'
    FROM tblStock AS A
    INNER JOIN
     (SELECT StockID from tblStock ORDER BY StockID ASC LIMIT 100) AS B
    ON A.StockID = B.StockID
    

    Result B:

    SELECT A.ProductID AS 'Product ID', '60' AS 'Quantity', SUM(A.Amount) AS 'Total Amount'
    FROM tblStock AS A
    INNER JOIN
     (SELECT StockID from tblStock ORDER BY StockID DESC LIMIT 60) AS B
    ON A.StockID = B.StockID
    

提交回复
热议问题