0

我有一个库存视图(列出所有单个库存和库存日期)和一个销售视图(列出所有销售和销售发生的日期)。

库存视图:

+----+------+-----+------------+
| ID | Item | Qty |    Date    |
+----+------+-----+------------+
|  1 | A    |   3 | 01/01/2000 |
|  2 | A    |   2 | 02/02/2000 |
|  3 | D    |   9 | 05/06/2000 |
|  4 | F    |  22 | 09/01/2001 |
|  5 | A    |  10 | 01/04/2001 |
|  6 | C    |  12 | 01/01/2002 |
+----+------+-----+------------+

销售视图:

+------+-----+------------+
| Item | Qty |    Date    |
+------+-----+------------+
| B    |   3 | 01/01/2001 |
| B    |  77 | 01/12/2001 |
| C    |   9 | 02/02/2002 |
| A    |  10 | 03/03/2002 |
| G    |   2 | 05/06/2002 |
| C    |   3 | 09/10/2012 |
+------+-----+------------+

我想加入这些表..但在这样做之前:

股票视图需要在 2 个日期参数 @StockFrom 和 @StockTo 之间进行过滤

销售视图需要在 2 个日期参数 @SalesFrom 和 @SalesTo 之间进行过滤

然后,销售视图需要按项目分组并汇总数量(因此尽管正在过滤日期字段,但需要删除它),然后在项目字段上加入库存视图。

因此,从本质上讲,我希望查看库存视图(但按日期过滤),并带有一个额外的列,显示该项目在 2 个日期之间发生的销售。

期望的输出:

+----+------+-----+------------+-------+
| ID | Item | Qty |    Date    | Sales |
+----+------+-----+------------+-------+
|  1 | A    |   3 | 01/01/2000 |    10 |
|  2 | A    |   2 | 02/02/2000 |    10 |
|  3 | D    |   9 | 05/06/2000 |     0 |
|  4 | F    |  22 | 09/01/2001 |     0 |
|  5 | A    |  10 | 01/04/2001 |    10 |
|  6 | C    |  12 | 01/01/2002 |    12 |
+----+------+-----+------------+-------+

提前感谢任何帮助!

4

2 回答 2

0
SELECT
  Stock.*,
  IFNULL(SUM(Sales.Qty),0) AS Sales
FROM Stock
LEFT JOIN Sales ON Stock.Item=Sales.Item
WHERE Stock.Date BETWEEN @StockFrom AND @StockTo
AND (
  Sales.Date BETWEEN @SalesFrom AND @SalesTo
  OR Sales.Date IS NULL
)
GROUP BY Stock.ID

这是针对 MySQL 的,因为您没有指定方言。SQLfiddle

编辑

SELECT
  Stock.ID AS ID,
  MIN(Stock.Item) AS Item,
  MIN(Stock.Qty) AS Qty,
  MIN(Stock.Date) AS Date,
  CASE WHEN SUM(Sales.Qty) IS NULL THEN 0 ELSE SUM(Sales.Qty) END AS Sales
FROM Stock
LEFT JOIN Sales ON Stock.Item=Sales.Item
WHERE Stock.Date BETWEEN @StockFrom AND @StockTo
AND (
  Sales.Date BETWEEN @SalesFrom AND @SalesTo
  OR Sales.Date IS NULL
)
GROUP BY Stock.ID

适用于 MS SQL ( SQLfiddle )

于 2013-04-16T11:27:20.413 回答
0

请尝试以下查询 MS Sql Server:

SELECT DISTINCT
    a.ID, 
    a.Item, 
    a.Qty, 
    a.Date, 
    ISNULL(SUM(b.Qty) OVER (PARTITION BY a.Item, a.[Date]), 0) Sales
FROM 
    StockView a LEFT JOIN SalesView b on a.Item=b.Item
于 2013-04-16T11:33:25.810 回答