admin

查询帮助:总计一些组的视图

sql

我正在寻找一种结构化视图查询的正确方法,以便在数据库方面包括一些总计等(该视图将由报表系统使用)。

相关数据结构

+---------+      +---------+
|WORKORDER|      |WPLABOR  |
|---------|      |---------|
|WONUM    |+---->|WONUM    |
|...      |  +   |LABORHRS |
+---------+  |   |RATE     |
             |   +---------+
             |
             |   +---------+
             |   |WPITEM   |
             |   |---------|
             +-->|WONUM    |
             |   |ITEMQTY  |
             |   |UNITCOST |
             |   +---------+
             |
             |   +----------------+
             |   |LONGDESCRIPTION |
             |   |----------------|
             +-->|LDKEY           |
                 |LDTEXT          |
                 +----------------+

目标

我想返回以下内容:

  • 工作订单中的各种项目
  • 所有人工成本的总和(每个工时*费率的总和)
  • 所有项目的总和(每个项目的数量*单位成本)
  • LDText CLOB

我已经在查询中显示了相关信息,但是正在努力解决人工和物料成本的总计问题。

到目前为止查询

 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';

谢谢你提供的所有帮助!


阅读 166

收藏
2021-07-01

共1个答案

admin

将表连接在一起时,每种可能的组合都会得到一行。因此,如果一个工作订单有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

2021-07-01