2013-10-02 44 views
-1

我有一個結果從SELECT語句中設置,我怎麼能不帶任何分隔符分割一列 這是我的結果分體式無定界符字符串中TSQL

Size TCount TDevice 
2  5  E01 
4.5 3  W02E01 

我想有這個

Size TCount TDevice 
2  5  E 
2  5  0 
2  5  1 
4.5  3  W 
4.5  6  0  (we have 2 times of 0) 
4.5  3  2 
4.5  3  1  

謝謝

回答

1
;with cte as 
(
select Size,TCount, 
     substring(TDevice, 1, 1) as Chars, 
     stuff(TDevice, 1, 1, '') as TDevice 
    from t1 
    union all 
    select Size,TCount, 
     substring(TDevice, 1, 1) as Chars, 
     stuff(TDevice, 1, 1, '') as TDevice 
    from cte 
    where len(TDevice) > 0 
) 
select distinct Size,sum(TCount),Chars 
from cte 
group by Size,Chars 

SQL Fiddle

優勢:它不需要任何User defined function (UDF)創建。

2

您可以加入一個輔助數字表。我使用spt_values進行演示,但您應該使用create a permanent one

WITH Nums 
    AS (SELECT number 
     FROM master..spt_values 
     WHERE type = 'P' 
       AND number BETWEEN 1 AND 1000), 
    Result(Size, TCount, TDevice) 
    AS (SELECT 2, 5,'E01' 
     UNION ALL 
     SELECT 4.5,3,'W02E01') 
SELECT Size, 
     COUNT(*) * TCount    AS TCount, 
     SUBSTRING(TDevice, number, 1) AS TDevice 
FROM Result 
     JOIN Nums 
     ON Nums.number <= LEN(TDevice) 
GROUP BY Size, 
      TCount, 
      SUBSTRING(TDevice, number, 1)