SQL Join帮助 - 在加入之前对表进行求和并应用过滤器

时间:2013-04-16 11:15:50

标签: sql join filter sum

我有一个股票视图(列出所有单独的股票和股票日期)和一个销售视图(列出了所有销售和销售发生的日期)。

股票查看:

+----+------+-----+------------+
| 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 |
+----+------+-----+------------+-------+

提前感谢您的帮助!

2 个答案:

答案 0 :(得分: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的,因为你没有指定diaclect。 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

答案 1 :(得分: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