如何在查询中获取逗号分隔值?

时间:2012-08-31 06:46:44

标签: sql sql-server

您好我有一张名为tbdSales

的表格
Brand     Cust_ID  Prd_ID

Aftron  44301   T3485
Aftron  44301   T0628
Aftron  44301   T2952
Aftron  44301   T1958
Aftron  44302   T1940
Aftron  44302   T1939
Aftron  44303   T2419
Aftron  44303   T2045

在此表中,我希望逗号中的Product_IDBrand&组分隔。 Cust_ID

我已经按如下方式生成了查询:

SELECT DISTINCT 
      Brand
    , Cust_ID
    , (
        SELECT DISTINCT second_id + ', ' 
        FROM tbdSales t2
        WHERE t2.Brand = t1.Brand AND t2.Cust_ID = t1.Cust_ID
        FOR XML PATH('')
    ) AS prd_ID into SalReport
FROM tbdSales t1 
GROUP BY Brand,Cust_ID

以上查询给出了结果。但是,如果记录更多(10,000)那么它需要花费很多时间,比如5分钟。

请让我知道减少查询完成时间的任何其他方式。

2 个答案:

答案 0 :(得分:1)

试试这个SQLFiddle example。它使用recursive query with CTE。为了获得更快的结果,您需要Brand,Cust_ID,Prd_ID上的索引:

with t2 as 
( select t0.*,
  row_number() over (partition by Brand,Cust_id order by Prd_id asc) G_id
  from
 (
  select distinct Brand,Cust_id,Prd_id from tbdSales
 ) t0 

 ),
  t1 as (
    select t.*,
           cast(Prd_id as varchar(max)) as m2
     from t2 t where g_id=1

 union all
 select b.*,
        cast(c.m2+','+b.Prd_id as varchar(max)) as m2
     from t2 b
         inner join t1 c
             on (c.g_id+1 = b.G_id) 
                and (b.Brand=c.Brand)
                and (b.Cust_id=c.Cust_Id)


)
  select brand,cust_id,M2 as Prd_id from 
  (
  select t1.*, 
         row_number() over (partition by Brand,Cust_id order by g_id desc) rn 
             from t1
  ) t3 where rn=1
 order by Brand,Cust_id

答案 1 :(得分:0)

SELECT distinct brand, Cust_ID, Replace( Replace( Replace(
                            (   select t2.Prd_ID
                                from @Sales as t2 
                                where t2.brand = t1.brand and t2.Cust_ID = t1.Cust_ID
                                For XML Raw)
                                 , '"/><row Prd_ID="', ', ')
                                 , '<row Prd_ID="', '')
                                 , '"/>', '') FROM  @Sales t1

嗨,试试这个。