访问查询(可能是SQL):当连接两个表时,如何防止第一个表中的重复值?

时间:2017-11-28 18:43:43

标签: sql ms-access ms-access-2016

我应该先说我没有SQL经验。我曾经尝试过观看视频和阅读教程,但我发现在真正了解正在发生的事情之前,我需要更广泛的了解。

这是我目前所处的位置;

订单

enter image description here

预测

enter image description here

财政日历

enter image description here

所需的加入查询

     Date    ||  Part Number  ||  Order QTY  ||  Forecast QTY
  10/9/2017  ||     AAA001    ||     200     ||      200
  10/9/2017  ||     AAA002    ||     400     ||      100
  10/9/2017  ||     AAA003    ||             ||       50
  10/9/2017  ||     AAA004    ||             ||      500

加入查询当前是如何

enter image description here

以下是我的设计视图查询,下面是我的 SQL 。有人可以协助调整SQL以使其符合所需的查询吗?

enter image description here

查询的SQL

SELECT [Fiscal Calendar].Date, Orders.[Part Number], 
    Orders.QTY, Forecast.QTY
FROM ([Fiscal Calendar] LEFT JOIN 
    Forecast 
    ON [Fiscal Calendar].Date = Forecast.Date
    ) LEFT JOIN 
    Orders ON [Fiscal Calendar].Date = Orders.Date
GROUP BY [Fiscal Calendar].Date, Orders.[Part Number], Orders.QTY, Forecast.QTY;

2 个答案:

答案 0 :(得分:1)

不确定您使用财政日历完成了什么,但这是我要采取的路线:

SELECT [Fiscal Calendar].DATE,
    Forecast.[Part Number],
    Sum(Orders.Qty) AS [Order QTY],
    Sum(Forecast.Qty) AS [Forcast QTY]
FROM [Fiscal Calendar]
INNER JOIN (
    Forecast LEFT JOIN Orders ON (Forecast.DATE = Orders.DATE)
    AND (Forecast.[Part Number] = Orders.[Part Number])
) ON [Fiscal Calendar].DATE = Forecast.DATE
GROUP BY [Fiscal Calendar].DATE,
Forecast.[Part Number];

答案 1 :(得分:0)

您错过了JOIN条件。我还认为你需要更多聚合:

SELECT [Fiscal Calendar].Date, Forecast.[Part Number],
       SUM(Orders.QTY), Forecast.QTY
FROM ([Fiscal Calendar] LEFT JOIN
      Forecast
      ON [Fiscal Calendar].Date = Forecast.Date
     ) LEFT JOIN
     Orders
     ON [Fiscal Calendar].Date = Orders.Date AND
        Forecast.[Part Number] = Orders.[Part Number]
GROUP BY [Fiscal Calendar].Date, Forecast.[Part Number], Forecast.QTY;

编辑:

我认为你可以用相关的子查询做你想做的事情:

SELECT [Fiscal Calendar].Date, Forecast.[Part Number],
       (SELECT SUM(Orders.QTY)
        FROM Orders
        WHERE [Fiscal Calendar].Date = Orders.Date AND
              Forecast.[Part Number] = Orders.[Part Number]
       ) as QTY,
       Forecast.QTY
FROM [Fiscal Calendar] LEFT JOIN
     Forecast
     ON [Fiscal Calendar].Date = Forecast.Date;