加入临时 Table 到实际 Table

Joining a Temp Table to Actual Table

我需要验证每个 订单 是否已被确认。问题是每个订单可以有多个代码。我的查询(使用 CASE 语句)将检查空白字段或带有字符串 "None" 的字段以验证订单是否已被确认。它会 return 适当的结果,但是 多个 行(每个可能的响应一次)我只需要 (1).

我正在尝试创建一个临时 table 将 return 适当的结果并将两个 table 加入(通过订单唯一 ID)在一起希望更正多行问题。这是代码:

DROP TABLE staging_TABLE;

CREATE TEMP TABLE staging_TABLE(
ORDERID varchar(256) ,
CODE varchar(256) );
/*Keeping data types consistent with the real table*/

INSERT INTO staging_TABLE
SELECT ORDERID,
CASE CODE
  WHEN 'None' THEN 'No'
  WHEN '' THEN 'No'
  ELSE 'Yes'
END
FROM ORDERS
WHERE UTCDATE > SYSDATE - 10
AND CODE IS NOT NULL;

SELECT R.QUESTION,
R.ORDERNAME,
T.CODE
FROM ORDERS R
INNER JOIN staging_TABLE T
ON R.ORDERID= T.ORDERID
WHERE R.UTCDATE > SYSDATE - 10
AND R.CODE IS NOT NULL
AND R.CATEGORY IS NOT NULL
AND R.UTCDATE IS NOT NULL
GROUP BY
         R.ORDER,
         T.CODE,
         R.ORDERNAME,
         R.CODE
ORDER BY 
R.ORDERNAME,
R.ORDER;

我这样做正确吗?或者这是正确的方法吗?

您可以如下使用 DISTINCT 关键字,这样就不需要临时文件 table:

SELECT DISTINCT QUESTION,
ORDERNAME,
CASE CODE
  WHEN 'None' THEN 'No'
  WHEN '' THEN 'No'
  ELSE 'Yes'
FROM ORDERS
WHERE UTCDATE > SYSDATE - 10
AND CODE IS NOT NULL
AND CATEGORY IS NOT NULL
AND UTCDATE IS NOT NULL
ORDER BY 2,3;

Am I doing this correctly? Or is this even the right approach?

没有。为此,您不需要临时 table。您的查询可能如下所示:

SELECT question, ordername
     , CASE WHEN code IN ('None', '') THEN 'No' ELSE 'Yes' END AS code
FROM   orders
WHERE  utcdate > sysdate - 10
AND    code IS NOT NULL
AND    category IS NOT NULL
GROUP  BY question, ordername, 3, "order"
ORDER  BY ordername, "order";
  • ORDER 是保留字。除非双引号,否则不能将其用作列名。那里有问题。

  • AND R.UTCDATE IS NOT NULL 是多余的。 WHERE R.UTCDATE > SYSDATE - 10

  • 无论如何都不能为 NULL 我的 GROUP BY 子句中的
  • 3 是对 CASE 表达式的位置引用。或者,您可以再次拼写:

....
GROUP  BY question, ordername
        , CASE WHEN code IN ('None', '') THEN 'No' ELSE 'Yes' END
        , "order"