需要SQL Server查询来聚合多行数据

时间:2018-05-23 14:31:35

标签: sql sql-server-2012 aggregate

我有一个表格,其中包含我需要将数据汇总到一行的客户信息。我的唯一标识符是我的客户编号。我怎样才能实现这一目标?这是我目前的数据:

        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

这是我期望的结果:

        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

1 个答案:

答案 0 :(得分:0)

您可以使用窗口功能:

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;