我是SQL的新用户,我可以在代码中使用一些帮助,请帮忙!
我有两个表:表1(物料主数据)和表2(采购历史记录)
表1示例
ITEM Warehouse Vendor
------------------------------
ITEM-0001 ATLANTA AMAZON
ITEM-0002 ATLANTA AMAZON
ITEM-0003 ATLANTA GOOGLE
ITEM-0004 ATLANTA AMAZON
表2示例
ITEM Purchase Date Price WAREHOUSE RECEIVE DATE
----------------------------------------------------------------
ITEM-0001 01/01/2017 $5 ATLANTA 03/05/2017
ITEM-0001 01/01/2017 $5.2 DENVER 02/03/2017
ITEM-0001 01/02/2017 $5.4 L.A. 05/07/2017
ITEM-0002 .... AND SO ON
我想要一个合并的结果集 - 像这样:
ITEM(T1) WAREHOUSE(T1) VENDOR(T1) Avg_Price(T2) LEADTIME
------------------------------------------------------------------
ITEM-0001 ATLANTA AMAZON 5.33333 65 DAYS
ITEM-0002 ATLANTA AMAZON ... so on
这是我的SQL代码:
SELECT
A.ITEM, A.WAREHOUSE, A.VENDOR, B.PRICE, B.LEADTIME
FROM
TABLE1 A, TABLE2 B
WHERE
A.ITEM = B.ITEM
AND B.PRICE = (SELECT AVG(B.PRICE)
FROM TABLE2 B
WHERE A.ITEM = B.ITEM
GROUP BY B.ITEM)
该部分增加了平均价格而没有任何问题。现在我在努力的地方就是当我想要添加LEADTIME时。知道如何编码吗?
LEADTIME是项目到达特定供应商和特定仓库的平均时间。例如,item0001在6天,8天和10天从供应商x到达仓库y,然后提前期将是该供应商和该仓库的这些天(8天)的平均值。
请帮忙!
提前致谢
编辑:在这之后提供帮助是我的新代码..谢谢!
SELECT B.ITEM,
A.VENDOR,
B.WAREHOUSE,
SUM(A.QUANTITY),
AVG(A.PRICE) AS AVGERAGE_PURCHASE PRICE,
AVG(A.RECEIVEDATE- A.PURCHASEDATE) AS LEADTIME,
FROM ITEMTABLE B
JOIN ITEMPURCHASETABLE A
ON (B.ITEM=A.ITEM AND B.WAREHOUE=A.WAREHOUSE)
WHERE A.PURCHASEDATE > 1170101
GROUP BY B.ITEM, B.WAREHOUSE, A.VENDOR
HAVING (MIN(A.PRICE)/MAX(A.PRICE)) !<0.1 AND COUNT(A.PRICE) >3
ORDER BY INVENTORY_COST DESC
新问题:日期是格式1YYMMDD有解决方案吗?