所以我有以下代码
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,因此新列返回INVOICED_QTY为空的空值
我尝试了多种方法:尝试合并到一个案例,将合并写为INVOICED然后在减法表达式中使用INVOICED,我尝试在同一行中使用coalesce作为减法(之间没有逗号,我觉得这是最好的解决方案,但无法编译)
答案 0 :(得分:3)
您无法在ALIAS
子句
WHERE
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)
原因如下:
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)
答案 1 :(得分:3)
在select-list和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)