SQL Server查询根据已取消的库存位置复制行
我当前的代码是复制每个项目的结果。我将前三个月在两个位置对每个项目的使用情况求和。我确实有更多的位置,但我将其限制在WHERE子句中。我认为查询显示了由于其他位置而产生的额外结果。有人能帮我清理代码吗 用法列为YYYYMM格式SQL Server查询根据已取消的库存位置复制行,sql,sql-server,tsql,date,join,Sql,Sql Server,Tsql,Date,Join,我当前的代码是复制每个项目的结果。我将前三个月在两个位置对每个项目的使用情况求和。我确实有更多的位置,但我将其限制在WHERE子句中。我认为查询显示了由于其他位置而产生的额外结果。有人能帮我清理代码吗 用法列为YYYYMM格式 select distinct u.location, u.item_id, l.qty_on_hand, u.inv_min, u.usage from inv_usage as u left join inventory_location a
select distinct
u.location, u.item_id, l.qty_on_hand, u.inv_min, u.usage
from
inv_usage as u
left join
inventory_location as l on u.inv_id = u.inv_id and l.location = u.location
where
u.year_period >= cast(convert(char(6), dateadd(month, -3, cast(convert(char(6), getdate(), 112) + '01' as date)), 112) as int)
and l.location in ('1', '2')
and u.location in ('1', '2')
库存量表:
l.location l.inv_id l.qty_on_hand l.inv_min
--------------------------------------------------
1 1 100 100
2 1 10 10
1 2 200 200
2 2 20 20
1 3 300 300
2 3 30 30
库存使用情况表:
u.location u.inv_id u.item_id u.inv_min u.year_period u.usage
-----------------------------------------------------------------------
1 1 item1 100 202002 100
2 1 item1 10 202002 10
1 1 item1 100 202002 100
2 1 item1 10 202002 10
1 1 item1 100 202002 100
2 1 item1 10 202002 10
1 2 item2 200 202003 200
2 2 item2 20 202003 20
1 2 item2 200 202003 200
2 2 item2 20 202003 20
1 2 item2 200 202003 200
2 2 item2 20 202003 20
1 3 item3 300 202004 300
2 3 item3 30 202004 30
1 3 item3 300 202004 300
2 3 item3 30 202004 30
1 3 item3 300 202004 300
2 3 item3 30 202004 30
我的期望结果汇总了每个位置前三个月的使用量,并显示了库存中的当前数量
?.location u.item_id l.qty_on_hand ?.inv_min u.usage
--------------------------------------------------------------
1 1 100 100 300
2 1 10 10 30
1 2 200 200 600
2 2 20 20 60
1 3 300 300 900
2 3 30 30 90
一个选项使用相关子查询:
select
il.*,
(
select sum(iu.usage)
from inventory_usage iu
where
iu.location = il.location
and iu.inv_id = il.inv_id
and iu.year_period >=
year(dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), 1))) * 100
+ month(dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), 1)))
and iu.year_period <
year(datefromparts(year(getdate()), month(getdate()), 1)) * 100
+ month(datefromparts(year(getdate()), month(getdate()), 1))
) usage
from inventory_location il
日期上的条件可能看起来很长,但在我看来,它们是最有效的过滤方式;它们使查询变得可搜索,并将利用有关库存位置、库存id、年份和期间的索引。请阅读一些改进问题的提示。包含DDL使我们不必猜测列的数据类型,例如,位置似乎是一个整数和一个字符串。