我正在寻找构建视图查询的正确方法,以便在数据库端包含一些总计等(视图将由报告系统使用)。
+---------+ +---------+
|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';
感谢您提供任何帮助!
答案 0 :(得分:2)
当您将表连接在一起时,每个可能的组合都会得到一行。因此,如果一个工单具有3个工作行和4个项目行,则这三个表的连接将返回12行。
避免这种情况的一种方法是在子查询中使用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