1

所以我有下面的代码

SELECT PICK_SO_NUMBER, CUSTOMER, SO_PRODUCT, DO_QUANTITY, DO_PACKING, DO_DATE,
COALESCE(INVOICED_QTY, 0) AS INVOICED_QTY, 
DO_QUANTITY-INVOICED_QTY AS NOT_INVOICED, 
INVOICE_PACKING 
FROM VW_TRAFFIC_PO_SIDE
WHERE  DO_QUANTITY > INVOICED_QTY OR (INVOICED_QTY IS NULL AND DO_QUANTITY IS NOT NULL)

合并下面的行,假设从 INVOICED_QTY 中减去 DO_QUANTITY,但是当 INVOICED_QTY 为 NULL 时,它不再减去 0,而是减去 null,因此新列返回 null,其中 INVOICED_QTY 为 null

我尝试了多种方法:尝试合并到一个案例,将合并写为 INVOICED,然后在减法表达式中使用 INVOICED,我尝试在减法的同一行中使用合并(中间没有逗号,我觉得这是解决方案效果最好,但无法编译)

4

2 回答 2

3

你不能ALIASWHERE子句上使用

SELECT  PICK_SO_NUMBER, 
        CUSTOMER, 
        SO_PRODUCT, 
        DO_QUANTITY, 
        DO_PACKING, 
        DO_DATE,
        COALESCE(INVOICED_QTY, 0) AS INVOICED_QTY, 
        DO_QUANTITY-INVOICED_QTY AS NOT_INVOICED, 
        INVOICE_PACKING 
FROM    VW_TRAFFIC_PO_SIDE
-- note that INVOICE_QTY in WHERE  DO_QUANTITY > INVOICED_QTY
-- does not compare the result of COALESCE(INVOICED_QTY, 0)
-- but to the original value of INVOICE_QTY
WHERE  DO_QUANTITY > COALESCE(INVOICED_QTY, 0) OR 
        (INVOICED_QTY IS NULL AND DO_QUANTITY IS NOT NULL)

原因如下:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句

WHERE子句位于SELECT设置 ALIAS 的地方)子句之后。

但如果您真的想使用该别名,请将其包装在子查询中,例如

SELECT  *
FROM
(
    SELECT  PICK_SO_NUMBER, 
            CUSTOMER, 
            SO_PRODUCT, 
            DO_QUANTITY, 
            DO_PACKING, 
            DO_DATE,
            COALESCE(INVOICED_QTY, 0) AS INVOICED_QTY, 
            DO_QUANTITY-INVOICED_QTY AS NOT_INVOICED, 
            INVOICE_PACKING 
    FROM    VW_TRAFFIC_PO_SIDE
) s
WHERE    DO_QUANTITY > INVOICED_QTY OR 
        (INVOICED_QTY IS NULL AND DO_QUANTITY IS NOT NULL)
于 2013-01-14T05:10:41.247 回答
3

当您在选择列表和 WHERE 子句中使用相同的别名“invoiced_qty”时,它会变得混乱。减法中的值是原始列值,而不是来自前一个选择列表项的合并值。WHERE 子句也是如此。

SELECT PICK_SO_NUMBER, CUSTOMER, SO_PRODUCT, DO_QUANTITY, DO_PACKING, DO_DATE,
       COALESCE(INVOICED_QTY, 0) AS INVOICED_QTY, 
       DO_QUANTITY - COALESCE(INVOICED_QTY, 0) AS NOT_INVOICED, 
       INVOICE_PACKING 
  FROM VW_TRAFFIC_PO_SIDE
 WHERE DO_QUANTITY > INVOICED_QTY
    OR (INVOICED_QTY IS NULL AND DO_QUANTITY IS NOT NULL)
于 2013-01-14T05:12:40.413 回答