How to separate a record to get the amount

时光总嘲笑我的痴心妄想 提交于 2019-12-12 07:38:54

问题


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.

tblStock
+----------+------------+----------+----------+------------+
+ Stock ID + Product ID + Quantity + Amount   + Date       +
+----------+------------+----------+----------+------------+
+        1 +       1001 +       50 +    10.00 + 2014-11-10 +
+----------+------------+----------+----------+------------+
+        2 +       1001 +       70 +    11.00 + 2014-11-11 +
+----------+------------+----------+----------+------------+
+        3 +       1001 +       30 +     9.90 + 2014-11-12 +
+----------+------------+----------+----------+------------+
+        4 +       1001 +       10 +    10.20 + 2014-11-13 +
+----------+------------+----------+----------+------------+

I need two result of below. Thanks

Result A (first 100 quantity)
+------------+----------+--------------+
+ Product ID + Quantity + Total Amount +
+------------+----------+--------------+
+       1001 +      100 +      1050.00 +
+------------+----------+--------------+

Result B (last 60 quantity)
+------------+----------+--------------+
+ Product ID + Quantity + Total Amount +
+------------+----------+--------------+
+       1001 +       60 +       619.00 +
+------------+----------+--------------+

回答1:


For first 100

select Product ID, sum(Quantity) as Quantity, sum(Amount) as TotalAmount from (SELECT * from tblstock order by tblStock.Stock ID ASC limit 100) t1 GROUP BY Date,Product ID

For last 60

select Product ID, sum(Quantity) as Quantity, sum(Amount) as Total Amount from (SELECT * from tblstock order by tblStock.Stock ID DESC limit 60) t1 GROUP BY Date,Product ID




回答2:


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


来源:https://stackoverflow.com/questions/27162988/how-to-separate-a-record-to-get-the-amount

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!