困惑于我的左连接

时间:2012-11-19 05:14:13

标签: sql ms-access

我在这个问题上wra my and and and and and and and and and and and and and and and and and and and and and and and and and实际上我正在尝试做的是:

计算销售的月平均值,同时排除适用于所有区域的假日类型1的天数(例如,我可以将其更改为特定区域的类型2)。

SELECT Year(Date) AS Year, Month(Date) AS Month, Avg(tblSales.Sales) AS AvgSales
FROM tblSales
LEFT JOIN tblHolidays
ON tblSales.[Date] >= tblHolidays.[Date From] AND tblSales.[Date] <= tblHolidays.[Date To] 
WHERE tblHolidays.[Date From] Is Null AND tblHolidays.[Type]<> 1 AND tblHolidays.[Region]<>"All"
GROUP BY Year(Date), Month(Date);

现在我不确定我是否理解这是否有效,而它确实会产生结果。我没有看到的是它告诉tblHolidays不使用类型2和类型3假期,或者与tblSales比较时适用于特定区域的假日。[日期]。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这就是你的意思。

SELECT Year(Date) AS Year, Month(Date) AS Month, Avg(tblSales.Sales) AS AvgSales
FROM tblSales
LEFT JOIN tblHolidays
     ON tblSales.[Date] >= tblHolidays.[Date From]
        AND tblSales.[Date] <= tblHolidays.[Date To]
        AND tblHolidays.[Type] = 1 AND tblHolidays.[Region] = "All"
WHERE tblHolidays.[Date From] Is Null
GROUP BY Year(Date), Month(Date);

LEFT JOIN用于从tblHolidays引入匹配,它匹配ON子句中所有条件的tblSales。在这种情况下,它说:

  1. 查找涵盖销售日期的假期,类型为1并影响“所有”区域。
  2. 由于LEFT JOIN特性,即使没有从tblHolidays找到匹配项,它也将保留tblSales中的所有行。接下来,如果找到匹配 ,我们会使用过滤器tblHolidays.[Date From] Is Null将其删除。由于tblHolidays.[Date From] 为空,因此找到了假期条件。