3

嗨,我有一张桌子叫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_ID与 group 分隔逗号BrandCust_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 分钟左右的时间。

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

4

2 回答 2

1

试试这个SQLFiddle 示例。它使用带有 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
于 2012-08-31T08:30:43.423 回答
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

你好,试试这个。

于 2012-08-31T08:41:37.770 回答