有很多订单的原始工作

时间:2017-06-13 15:58:14

标签: sql

我已经在这一段时间了,我正在尝试写另一个子查询来减去[总合同] - [总费用]。这两个子查询运行正常,但是我无法编写另一个子查询来为所需的[profit]列减去它们。大多数时候我尝试的查询只是返回说子查询返回了多个值..非常感谢任何帮助!这是我到目前为止所得到的:

SELECT MAN_PROD_ORDER.PROD_ORDER_NUM,
(SELECT SUM(SAL_SALES_ORDER.AMOUNT_INCLUDING_TAX)
FROM SAL_SALES_ORDER
WHERE (SAL_SALES_ORDER.ORIG_SALES_ORDER_ID = MAN_PROD_ORDER.SALES_ORDER_ID or SAL_SALES_ORDER.SALES_ORDER_ID = MAN_PROD_ORDER.SALES_ORDER_ID)
      and SAL_SALES_ORDER.SAL_ORDER_STATUS_ID not in (6, 8)) as [total contract],
(SELECT SUM(PROD_ORDER_LEDGER_ENTRY.TOTAL_COST) 
FROM PROD_ORDER_LEDGER_ENTRY
WHERE MAN_PROD_ORDER.PROD_ORDER_ID = PROD_ORDER_LEDGER_ENTRY.PROD_ORDER_ID AND PROD_ORDER_LEDGER_ENTRY.ENTRY_TYPE_ID = 1) as [total cost]
FROM MAN_PROD_ORDER 

1 个答案:

答案 0 :(得分:0)

应该以某种方式工作:

SELECT MAN_PROD_ORDER.PROD_ORDER_NUM
      ,SUM(SAL_SALES_ORDER.AMOUNT_INCLUDING_TAX) AS total_contract
      ,SUM(PROD_ORDER_LEDGER_ENTRY.TOTAL_COST) AS total_cost
      ,SUM(SAL_SALES_ORDER.AMOUNT_INCLUDING_TAX - PROD_ORDER_LEDGER_ENTRY.TOTAL_COST) as profit
  FROM MAN_PROD_ORDER 
  LEFT OUTER JOIN SAL_SALES_ORDER
    ON (SAL_SALES_ORDER.ORIG_SALES_ORDER_ID = MAN_PROD_ORDER.SALES_ORDER_ID OR
        SAL_SALES_ORDER.SALES_ORDER_ID      = MAN_PROD_ORDER.SALES_ORDER_ID)
   AND SAL_SALES_ORDER.SAL_ORDER_STATUS_ID NOT IN (6, 8)
  LEFT OUTER JOIN PROD_ORDER_LEDGER_ENTRY
    ON MAN_PROD_ORDER.PROD_ORDER_ID = PROD_ORDER_LEDGER_ENTRY.PROD_ORDER_ID 
   AND PROD_ORDER_LEDGER_ENTRY.ENTRY_TYPE_ID = 1
GROUP BY MAN_PROD_ORDER.PROD_ORDER_NUM