4

我正在构建一个库存系统,并决定将每个产品的余额(每次更新)存储到下表中:

+------------+--------------+---------+------+
| Product_id | Warehouse_id | Balance | Date |
+------------+--------------+---------+------+

例子:

员工在warehouse_id 5 的product_id 123 中添加10 件

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 123        | 5            | 10      | 2013-09-16  |
+------------+--------------+---------+-------------+

然后工作人员将 3 件添加到仓库 ID 5 中的产品 234,并将 5 件添加到仓库 ID 5 中的 123,

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 123        | 5            | 10      | 2013-09-16  |
| 234        | 5            | 3       | 2013-09-18  |
| 123        | 5            | 15      | 2013-09-21  |
+------------+--------------+---------+-------------+

*注意日期栏

现在让我再添加几行

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 123        | 5            | 10      | 2013-09-16  |
| 234        | 5            | 3       | 2013-09-18  |
| 123        | 5            | 15      | 2013-09-21  |
| 123        | 5            | 18      | 2013-09-24  |
| 234        | 5            | 10      | 2013-09-26  |
| 123        | 5            | 22      | 2013-09-29  |
+------------+--------------+---------+-------------+

如何运行查询以获取截至 2013 年 9 月 25 日的所有产品余额?

这意味着我需要以下结果:

+------------+--------------+---------+-------------+
| Product_id | Warehouse_id | Balance | Date        |
+------------+--------------+---------+-------------+
| 234        | 5            | 3       | 2013-09-18  |
| 123        | 5            | 18      | 2013-09-24  |
+------------+--------------+---------+-------------+

简而言之,我需要每个 product_id 的最新行(按日期)。

任何帮助将不胜感激!

4

3 回答 3

2

假设每个仓库都维护产品的余额,您可以这样做

SELECT t.product_id, t.warehouse_id, t.balance, t.date
  FROM table1 t JOIN 
(
  SELECT warehouse_id, product_id, MAX(date) date
    FROM table1
   WHERE date <= '2013-09-25'
   GROUP BY warehouse_id, product_id
) q
    ON t.warehouse_id = q.warehouse_id
   AND t.product_id = q.product_id
   AND t.date = q.date

输出:

| PRODUCT_ID | 仓库 ID | 余额 | 日期 |
|------------|--------------|---------|------------ -|
| 234 | 5 | 3 | 2013-09-18 |
| 123 | 5 | 18 | 2013-09-24 |

这是SQLFiddle演示

于 2013-09-16T10:49:14.267 回答
0
SELECT * 
FROM TABLE 
WHERE (PRODUCT_ID, DATE) IN
     (SELECT PRODUCT_ID, MAX(DATE) FROM TABLE
      WHERE DATE <= '2013-09-25'     
       GROUP BY PRODUCT_ID )
于 2013-09-16T10:47:58.047 回答
0

询问:

SQLFIDDLE示例

  SELECT *
  FROM table1 t 
  WHERE t.`Date` = (SELECT MAX(t2.`Date`)
                  FROM Table1 t2
                  WHERE t2.`Date` <= '2013-09-25'
                  AND t2.product_id = t.product_id)
于 2013-09-16T11:01:16.880 回答