I have a table with customer information that I need to aggregate the data for into one row. My unique identifier is my customer number. How can i achieve that? Here is my current data:
ID CUST_NUM CUSTOMER_NAME BOUGHT_PRODUCT_A BOUGHT_PRODUCT_B BOUGHT_PRODUCT_C BOUGHT_PRODUCT_D
1 125654 IHOP NULL NULL NULL YES
2 125654 I.H.O.P. YES NULL NO YES
3 125654 IHOP INC. YES NULL NULL NULL
And this is my desired outcome:
ID CUST_NUM CUSTOMER_NAME BOUGHT_PRODUCT_A BOUGHT_PRODUCT_B BOUGHT_PRODUCT_C BOUGHT_PRODUCT_D
1 125654 IHOP,I.H.O.P.,IHOP INC. NULL NULL NULL YES
You can use window function:
select distinct CUST_NUM,
stuff ((select distinct ',' +CUSTOMER_NAME
from table
where t.CUST_NUM = CUST_NUM for xml path('')
), 1,1, ''
) as CUSTOMER_NAME,
first_value(BOUGHT_PRODUCT_A) over (partition by CUST_NUM order by ID) BOUGHT_PRODUCT_A,
first_value(BOUGHT_PRODUCT_B) over (partition by CUST_NUM order by ID) BOUGHT_PRODUCT_B,
first_value(BOUGHT_PRODUCT_C) over (partition by CUST_NUM order by ID) BOUGHT_PRODUCT_C,
first_value(BOUGHT_PRODUCT_D) over (partition by CUST_NUM order by ID) BOUGHT_PRODUCT_D
from table t;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.