我正在寻找一种结构化视图查询的正确方法,以便在数据库方面包括一些总计等(该视图将由报表系统使用)。
+---------+ +---------+ |WORKORDER| |WPLABOR | |---------| |---------| |WONUM |+---->|WONUM | |... | + |LABORHRS | +---------+ | |RATE | | +---------+ | | +---------+ | |WPITEM | | |---------| +-->|WONUM | | |ITEMQTY | | |UNITCOST | | +---------+ | | +----------------+ | |LONGDESCRIPTION | | |----------------| +-->|LDKEY | |LDTEXT | +----------------+
我想返回以下内容:
我已经在查询中显示了相关信息,但是正在努力解决人工和物料成本的总计问题。
SELECT WORKORDER.WONUM, WORKORDER.ACTLABHRS, WORKORDER.LOCATION, WORKORDER.STATUS, WORKORDER.WO7, -- Requester WORKORDER.WO8, -- Extension WORKORDER.WO9, -- Location WORKORDER.LEADCRAFT, WORKORDER.WO11, -- Extension WORKORDER.GLACCOUNT, WORKORDER.WO10, -- Contact WORKORDER.DESCRIPTION, -- Short description WORKORDER.WO6, -- Plant rearrangement (YORN / boolean value) LONGDESCRIPTION.LDTEXT, WPLABOR.LABORHRS, WPLABOR.RATE, WPITEM.ITEMQTY, WPITEM.UNITCOST FROM MAXIMO.WORKORDER LEFT OUTER JOIN MAXIMO.LONGDESCRIPTION ON WORKORDER.WONUM = CAST(LONGDESCRIPTION.LDKEY as varchar(22)) LEFT OUTER JOIN MAXIMO.WPLABOR ON WORKORDER.WONUM = WPLABOR.WONUM LEFT OUTER JOIN MAXIMO.WPITEM ON WORKORDER.WONUM = WPITEM.WONUM WHERE LONGDESCRIPTION.LDOWNERTABLE='WORKORDER' AND LONGDESCRIPTION.LDOWNERCOL = 'DESCRIPTION';
谢谢你提供的所有帮助!
将表连接在一起时,每种可能的组合都会得到一行。因此,如果一个工作订单有3个工作行和4个项目行,则三个表的联接将返回12行。
避免这种情况的一种方法是group by在子查询中处理工作订单:
group by
SELECT WORKORDER.WONUM , LONGDESCRIPTION.LDTEXT , ... other columns ... , Labor.LaborCost , Item.ItemCost FROM MAXIMO.WORKORDER LEFT JOIN MAXIMO.LONGDESCRIPTION ON WORKORDER.WONUM = CAST(LONGDESCRIPTION.LDKEY as varchar(22)) LEFT JOIN ( SELECT WONUM , SUM(WPLABOR.LABORHRS * WPLABOR.RATE) as LaborCost FROM MAXIMO.WPLABOR GROUP BY WOWNUM ) Labor ON WORKORDER.WONUM = Labor.WONUM LEFT JOIN ( SELECT WONUM , SUM(WPITEM.ITEMQTY * WPITEM.UNITCOST) as ItemCost FROM MAXIMO.WPITEM GROUP BY WOWNUM ) Item ON WORKORDER.WONUM = Item.WONUM