2017-08-30 159 views
0

對不起,措辭不當的問題,但我使用下面的查詢鞏固客戶記錄:根據同一選擇查詢中的另一個值選擇合併值?

select 
customer_key 
,FIRST_VALUE(name   IGNORE NULLS) OVER(PARTITION BY customer_key ORDER BY last_updated_date desc ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS NAME 
,FIRST_VALUE(county  IGNORE NULLS) OVER(PARTITION BY customer_key ORDER BY last_updated_date desc ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS COUNTRY 
,FIRST_VALUE(country_code IGNORE NULLS) OVER(PARTITION BY customer_key ORDER BY last_updated_date desc ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS COUNTRY_CODE 
from   customers cust 

這將選擇最近使用的customer_key客戶記錄。但對於國家/地區,我需要國家/地區代碼與國家/地區處於同一行,並使用country字段作爲驅動程序,但country_code列是NOT NULL字段。

例如,該原始數據:

customer Country Country_Code Date 
Dave  NULL  0   30/08/2017 
David  UK  1   29/08/2017 

需要顯示爲:

customer Country Country_Code 
Dave  UK  1 
Dave  UK  1 

但使用select查詢我目前使用我得到這個:

customer Country Country_Code 
Dave  UK  0 
Dave  UK  0 

有什麼建議嗎?

回答

1

以下查詢應該可以工作。

SELECT FIRST_VALUE(NAME IGNORE NULLS) OVER (
     PARTITION BY customer_key ORDER BY last_updated_date DESC ROWS BETWEEN UNBOUNDED PRECEDING 
       AND UNBOUNDED FOLLOWING 
     ) AS NAME 
    ,FIRST_VALUE(county IGNORE NULLS) OVER (
     PARTITION BY customer_key ORDER BY last_updated_date DESC ROWS BETWEEN UNBOUNDED PRECEDING 
       AND UNBOUNDED FOLLOWING 
     ) AS COUNTRY 
    ,FIRST_VALUE((
      CASE 
       WHEN county IS NULL 
        THEN NULL 
       ELSE country_code 
       END 
      ) IGNORE NULLS) OVER (
     PARTITION BY customer_key ORDER BY last_updated_date DESC ROWS BETWEEN UNBOUNDED PRECEDING 
       AND UNBOUNDED FOLLOWING 
     ) AS COUNTRY_CODE 
FROM customers cust; 
相關問題