对于措辞不好的问题感到抱歉,但我正在使用以下查询整合客户记录:
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_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
但是使用我正在使用的选择查询,我得到了这个:
customer Country Country_Code
Dave UK 0
Dave UK 0
有什么建议吗?
答案 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;