我需要创建一个查询,以30天,60天和90天的间隔显示财务和实际日期的库存总计。我有两个表(inventtrans和inventdim)包含连接的数据。我希望它是一个查询...
这些是我的查询:
SELECT it.ITEMID, it.DATAAREAID, inventdim.INVENTBATCHID, inventdim.INVENTLOCATIONID, SUM(it.QTY) AS QTY
FROM [dbo].[INVENTTRANS] IT
JOIN Inventdim on inventdim.inventdimid = it.inventdimid and it.DATAAREAID = inventdim.DATAAREAID
WHERE DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 0 and 180 OR DATEDIFF(day,it.DATEFINANCIAL,getdate()) between 0 and 180
GROUP BY it.ITEMID, it.DATAAREAID, inventdim.INVENTBATCHID, inventdim.INVENTLOCATIONID
GO
SELECT it.ITEMID, it.DATAAREAID, inventdim.INVENTBATCHID, inventdim.INVENTLOCATIONID, SUM(it.QTY) AS QTY
FROM [dbo].[INVENTTRANS] IT
JOIN Inventdim on inventdim.inventdimid = it.inventdimid and it.DATAAREAID = inventdim.DATAAREAID
GROUP BY DATEDIFF(day,it.DATEPHYSICAL,getdate()), DATEDIFF(day,it.DATEFINANCIAL,getdate()), it.ITEMID, it.DATAAREAID, inventdim.INVENTBATCHID, inventdim.INVENTLOCATIONID
GO
SELECT distinct it.ITEMID, it.DATAAREAID, inventdim.INVENTBATCHID, inventdim.INVENTLOCATIONID, SUM(it.QTY) AS QTY
FROM [dbo].[INVENTTRANS] IT
JOIN Inventdim on inventdim.inventdimid = it.inventdimid and it.DATAAREAID = inventdim.DATAAREAID
GROUP BY it.ITEMID, it.DATAAREAID, inventdim.INVENTBATCHID, inventdim.INVENTLOCATIONID, it.DATEPHYSICAL, it.DATEFINANCIAL
HAVING DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 0 and 30
OR DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 31 and 60
OR DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 61 and 90
OR DATEDIFF(day,it.DATEPHYSICAL,getdate()) > 90
GO
我已经能够获得每个项目的总库存变化,但是我无法为每个存储桶获得单独的列。我的SQL无法及时处理此问题,我正在寻求帮助。
我需要itemid,dataareaid,inventbatchid,inventlocationid,30、60、90、90 +列,而我目前只看到我的QTY列,我认为这是对项目的那些交易进行了总和,而与存储桶无关。
我尝试获得所需东西的方式也不同,请大声笑!
答案 0 :(得分:0)
细节上含糊不清,但我认为您希望遵循这些原则。
SELECT distinct it.ITEMID
, it.DATAAREAID
, inventdim.INVENTBATCHID
, inventdim.INVENTLOCATIONID
, SUM(it.QTY) AS QTY
, [0-30] = sum(case when DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 0 and 30 then 1 end)
, [31-60] = sum(case when DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 31 and 60 then 1 end)
, [61-90] = sum(case when DATEDIFF(day,it.DATEPHYSICAL,getdate()) between 61 and 90 then 1 end)
, [>90] = sum(case when DATEDIFF(day,it.DATEPHYSICAL,getdate()) > 90 then 1 end)
FROM [dbo].[INVENTTRANS] IT
JOIN Inventdim on inventdim.inventdimid = it.inventdimid and it.DATAAREAID = inventdim.DATAAREAID
where it.DATEPHYSICAL > convert(date, getdate())
GROUP BY it.ITEMID
, it.DATAAREAID
, inventdim.INVENTBATCHID
, inventdim.INVENTLOCATIONID
, it.DATEFINANCIAL