我有一张表是我的库存,我有另一张表是库存商店,现在我想根据查询表日期从Stock表中获取当前周记录。
查询对我来说很好,除了有些日子没有记录,但我也要显示零。
select datename(dw,DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(HOUR, 11, inquiry_tbl.order_date)))) date
, count(stock_id) as TotalShipment
from stock_tbl
left join inquiry_tbl on stock_tbl.Inquiry_id = inquiry_tbl.Inquiry_id
where stock_tbl.inquiry_id = inquiry_tbl.inquiry_id
and DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(HOUR, 11, inquiry_tbl.order_date)))
>=
DATEADD(wk, DATEDIFF(wk,0,DATEADD(HOUR, 11, getdate())), -2)
and
DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(HOUR, 11, inquiry_tbl.order_date)))
<=
DATEADD(wk, DATEDIFF(wk,0,DATEADD(HOUR, 11, getdate())), 4)
group by DATEADD(dd, 0, DATEDIFF(dd, 0, DATEADD(HOUR, 11, inquiry_tbl.order_date)))
任何解决方案?
答案 0 :(得分:2)
您需要从where子句中删除stock_tbl.inquiry_id = inquiry_tbl.inquiry_id
。它将消除否则将包含的行 - 它有效地将左外连接更改为内连接:
编辑:我刚刚意识到您正在按照正在加入的列进行分组。在这种情况下,您的联接也会向后退。试试这个:
编辑:从您的评论中我假设两个表中都没有缺少日期的行。在这种情况下,您必须在查询中引入这些日子 - 这是使用values
语句执行此操作的示例,如果性能有问题,您可能需要考虑使用日期表:
declare @start_date datetime = DATEADD(wk, DATEDIFF(wk, 0, DATEADD(HOUR, 11, getdate())), -2)
select
week.day date,
count(stock_id) as TotalShipment
from
(select DATEADD(dd, d, @start_date) day
from (values (0),(1),(2),(3),(4),(5),(6)) x(d)) week
left join
inquiry_tbl on inquiry_tbl.order_date between week.day and week.day + 1
left join
stock_tbl on stock_tbl.Inquiry_id = inquiry_tbl.Inquiry_id
group by
week.day
答案 1 :(得分:1)