在 SQL 中显示每个日历周一行
我有一个 SQL 查询,可以按商品、按周提取单位销售额:
SELECT sls_vendor,
sls_item,
sls_units,
DATEPART(week, sls_week) AS sls_date
FROM mytable
假设我正在查看 8 周的时间段,但并非每个商品/供应商组合都有完整 8 周的销售额。但是我需要我的查询在该实例中显示空值。因此,无论是否存在,查询都会为每个项目/供应商组合返回 8 行。
我尝试创建一个包含数字 28 到 35 的临时表,并对上面的查询执行左连接,但没有显示空值。结果与单独运行原始查询没有什么不同。
我可以想到如何使用交叉表/透视查询来完成此操作,但这不是联接应该做的事情吗?
编辑:更新以显示我的加入查询。 Datetable
只有 8 行,每个日历周有 1 个增量数字。
SELECT * FROM @datetable
LEFT JOIN
(SELECT
sls_vendor,
sls_item,
sls_units,
datepart(week,sls_week) AS sls_date
FROM mytable) AS QRY
ON temp_week = qry.sls_date
I have a SQL query which pulls unit sales by item, by week:
SELECT sls_vendor,
sls_item,
sls_units,
DATEPART(week, sls_week) AS sls_date
FROM mytable
Assume I'm looking at a 8 week period, but not every item/vendor combination has a full 8 weeks of sales. However I need my query to show a null value in that instance. So the query would return 8 rows for each item/vendor combination regardless of existence.
I tried creating a temp table which has the numbers 28 to 35 and performing a left join on the query above, but that doesn't show null values. The results are no different than running the original query alone.
I can think of how this would be done using a crosstab/pivot query, but isn't this something the join should be doing?
Edit: Updated to show my join query. Datetable
just has 8 rows with 1 incremental number for each calendar week.
SELECT * FROM @datetable
LEFT JOIN
(SELECT
sls_vendor,
sls_item,
sls_units,
datepart(week,sls_week) AS sls_date
FROM mytable) AS QRY
ON temp_week = qry.sls_date
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的方法应该可以正常工作:
输出:
编辑:如果您想包含每个销售供应商的所有周值,请包含与不同供应商选择的交叉连接:
输出:
Your method should work just fine:
Output:
Edit: If you want to include all week values for every sales vendor, include a cross join with the distinct selection of vendors:
Output:
它对你有用吗?
Does it work for you?
以下查询适用于 Data.StackExchange。 请参阅此处。按分数计算,它每周都会排名第一。
2008 年第 38 周之前的每一行都是空的,除了周和年。以及 2011 年第 35 周之后的行。
但是,如果您编辑查询并删除
OR row IS NULL
,则查询的行为就像INNER JOIN
我的猜测是,您的 WHERE 中有一些内容引用了“RIGHT”表。只需添加
OR [rightTable.field] IS NULL
就可以了。The following query works in Data.StackExchange. See here. It gets the top Post per week by score.
Every row prior to the 38 week in 2008 is empty except for week and year. As well as the rows after the 35 week in 2011.
However if you edit the query and remove
OR row IS NULL
the query will act just as if it were anINNER JOIN
My guess is that there's somthing in your WHERE that's referring to the "RIGHT" table. Just add
OR [rightTable.field] IS NULL
and you'll be fine.