如何将没有作为零值销售的项目的周添加到我的SQL查询中?

时间:2016-11-28 12:13:57

标签: sql ms-access ms-access-2013

基本上我在下面有这个查询,它给我每周的销售数量,但是它会跳过没有特定商品销售的周数。我希望它也显示为0值。 顺便说一句,是否有可能合并下面的两个查询?我尝试过但无法使用连接。

SELECT tblWeek.WeekNum, [Query - Sales].ModelName, Count([Query - Sales].OutDate) AS CountOfOutDate
FROM tblWeek LEFT JOIN [Query - Sales] ON tblWeek.WeekNum = [Query - Sales].WeekNumber
GROUP BY tblWeek.WeekNum, [Query - Sales].ModelName
HAVING ((([Query - Sales].ModelName) Is Not Null))
 ORDER BY [Query - Sales].ModelName;

查询 - 销售:

SELECT DDL_Items.ModelName, DDL_Items.OutDate, DDL_Models.Type, DatePart("ww",[OutDate],2) AS WeekNumber
FROM DDL_Models INNER JOIN DDL_Items ON DDL_Models.ModelName = DDL_Items.ModelName;

enter image description here

谢谢你,最诚挚的问候,

旧金山

2 个答案:

答案 0 :(得分:1)

您要做的第一件事是在您的模型名称和周之间创建一个笛卡尔联接。类似的东西:

SELECT DISTINCT [Query - Sales].ModelName, tblWeek.WeekNum
FROM [Query - Sales]
LEFT JOIN tblWeek 

这将为每个型号名称每周创建一条记录。

然后,您想要将实际数据加入此查询:

SELECT qryA.*, Count([Query - Sales].OutDate) AS CountOfOutDate
FROM (
SELECT DISTINCT [Query - Sales].ModelName, tblWeek.WeekNum
FROM [Query - Sales]
LEFT JOIN tblWeek 
) as qryA
LEFT JOIN [Query - Sales]   
   ON tblWeek.WeekNum = qryA.WeekNumber
GROUP BY tblWeek.WeekNum, qryA.ModelName
HAVING qryA.ModelName Is Not Null
ORDER BY qryA.ModelName;

答案 1 :(得分:0)

以下完整代码,以防有人正在寻找答案:

SELECT qryA.ModelName, qryA.WeekNum, Count([Query - Sales].OutDate) AS CountOfOutDate
FROM qryA LEFT JOIN [Query - Sales] ON qryA.WeekNum = [Query - Sales].WeekNumber
GROUP BY qryA.ModelName, qryA.WeekNum;