2012-08-31 59 views
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_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分鐘的時間。

請讓我知道任何其他方式來減少查詢完成時間。

+0

試試'CONCAT'凝聚劑。 –

+3

你有品牌和cust_id專欄的索引嗎? – hgulyan

+0

不,我沒有它 – user1632718

回答

1

試試這個SQLFiddle example。它使用recursive query with CTE。爲了更快的結果,你需要對品牌,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 
+0

嗨感謝您的重播。通過使用上面的查詢我geting的結果,但仍然是時間是同一問題 – user1632718

+0

您應該創建索引以更快地獲得結果。例如: 'CREATE INDEX Idx_tbdSales_Brand ON tbdSales(Brand); CREATE INDEX Idx_tbdSales_Cust_ID ON tbdSales(Cust_ID); CREATE INDEX Idx_tbdSales_Prd_ID ON tbdSales(Prd_ID);' – valex

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 

嗨,試試這個。

+0

嗨感謝您的重播。通過使用上面的查詢我geting的結果,但仍然是時間同樣的問題 – user1632718