2014-09-25 163 views
2

鑑於許多類型和數量的每種類型出現的,我想產生這樣的事情在T-SQL:生成SQL行

Occurrence | Type 
----------------- 
     0 | A 
     1 | A 
     0 | B 
     1 | B 
     2 | B 

的種類數量和出現的每數類型以不同表格中的值呈現。

雖然我能做到這一點與while循環,我正在尋找一個更好的解決方案。

謝謝!

+1

也請分享你的其他表。 – AK47 2014-09-25 12:56:09

+2

在問你的問題之前,你有嘗試過嗎? – 2014-09-25 12:56:17

+0

[你嘗試過什麼?](http://whathaveyoutried.com)最起碼,發佈數據樣本或(更好)創建[SQL撥弄]一個簡單的例子(http://sqlfiddle.com) – Barranka 2014-09-25 13:51:54

回答

2

這適用於我將使用的數字表。

SELECT Occurrence = ROW_NUMBER() OVER (PARTITION BY Type ORDER BY Type) - 1 
    , Type 
FROM Numbers num 
INNER JOIN #temp1 t 
ON num.n BETWEEN 1 AND t.Occurrence 

測試這個樣本數據:

create table #temp1(Type varchar(10),Occurrence int) 
insert into #temp1 VALUES('A',2) 
insert into #temp1 VALUES('B',3) 

如何創建一個數表? http://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1

+0

謝謝,那有效。雖然一個次要的事情 - 關於n介於1和t.Occurrence應該是: ON n.COLUMNAME介於1和T.Occurrence – mo5470 2014-09-25 13:10:05

+0

@ mo5470:在我的電話號碼錶'N'是列名。但是你是對的,這有點令人困惑,因爲表的別名也是'n'。我已經改變了這一點。 – 2014-09-25 13:28:03

1

如果你有一張表typenum,你有兩種方法。一種方法是使用遞歸的熱膨脹係數:

with CTE as (
     select type, 0 as occurrence, num 
     from table t 
     union all 
     select type, 1 + occurrence, num 
     from cte 
     where occurrence + 1 < num 
    ) 
select cte.* 
from cte; 

您可能需要如果數量超過100

另一種方式是在一個數字表加入到設置MAXRECURSION選項。爲此,SQL Server使用spt_values

select s.number - 1 as occurrence, t.type 
from table t join 
    spt_values s 
    on s.number <= t.num ;