2015-06-22 102 views
0

我是SQL新手,遇到了一些解決問題的麻煩。我正在重寫一個腳本,以便能夠與收到電子郵件的客戶進行匹配。以前我一直在使用會話表如下:將表格從插入表格中插入

DECLARE GLOBAL TEMPORARY TABLE EMAIL_SENDS 
     (
     ACCOUNT_NUMBER  INT 
     ) 
WITH REPLACE 
ON COMMIT PRESERVE ROWS 
; 

INSERT INTO SESSION.EMAIL_SENDS 
SELECT  ACCOUNT_NUMBER 
FROM  SENT_DATA A 
    JOIN MAIN_TABLE B 
     ON A.CLIENT_ID_SUBKEY = B.CUST_ID 
     OR A.CLIENT_ID_SUBKEY = B.OLD_ID 
WHERE  SEND_ID = 123456 
GROUP BY ACCOUNT_NUMBER 
; 

然後把數據當我剛使用CASE WHEN C.ACCOUNT_NUMBER IS NOT NULL THEN 1 ELSE 0 END加入與EMAIL_SENDS檢舉誰擁有和MAIN_TABLE尚未收到電子郵件。

但是,我想改進這個過程,並向MAIN_TABLE添加一列,說明誰收到了電子郵件,誰沒有收到。

這是我的腳本至今:

ALTER TABLE MAIN_TABLE 
ADD EMAILED INT 
; 

INSERT INTO MAIN_TABLE 
SELECT  EMAILED 
CASE WHEN ACCOUNT_NUMBER IS NOT NULL THEN 1 ELSE 0 END 
    FROM (SENT_DATA A 
      JOIN MAIN_TABLE B 
      ON A.CLIENT_ID_SUBKEY = B.CUST_ID 
      OR A.CLIENT_ID_SUBKEY = B.OLD_ID 
      WHERE  SEND_ID = 123456 
      GROUP BY ACCOUNT_NUMBER 
      ) 
; 

由於我是新來的SQL我無法弄清楚我要去哪裏錯了(儘管它可能是顯而易見的任何人精通它)。

+0

分享你的表結構....有兩列的主表? EMIALED,ACCOUNT_NUMBER –

+0

您確定要'INSERT INTO MAIN_TABLE',而不是'UPDATE MAIN_TABLE'嗎? – mustaccio

回答

0

試試這個。與此(電郵發送,ACCOUNT_NUMBER)取代來自主表列名

INSERT INTO MAIN_TABLE (EMAILED,ACCOUNT_NUMBER) 
SELECT  EMAILED, 
CASE WHEN ACCOUNT_NUMBER IS NOT NULL THEN 1 ELSE 0 END 
    FROM (SENT_DATA A 
      JOIN MAIN_TABLE B 
      ON A.CLIENT_ID_SUBKEY = B.CUST_ID 
      OR A.CLIENT_ID_SUBKEY = B.OLD_ID 
      WHERE  SEND_ID = 123456 
      GROUP BY ACCOUNT_NUMBER 
      ) 
;