2013-11-20 71 views
0

我有一個項目我工作的需要,我組記錄,看起來像下面,我需要一些幫助......TSQL:分組大量數據

這裏的現有結構:

表:形式

FormID  FormName  FormType  GroupID <<< New column 
---------------------------------------------- 
1   Form1  1 
2   Form1  1 
3   Form2  2 
4   Form2  2 
5   Form2  2 

表:字段

FieldID  FormID  FieldLabel  IsRequired OtherField... 
---------------------------------------------------------------------------- 
1   1   Label1   1   x 
2   1   Label2   0   y 
3   1   Label3   0   z 
4   2   Label1   1   x 
5   2   Label2   0   y 
6   2   Label3   0   z 
7   3   Label1   1   x 
8   3   Label2   0   y 
9   3   Label3   0   z 
10   4   Label1   1   x 
11   4   Label2   0   y 
12   4   Label3   0   z 
13   5   Label1   1   a 
14   5   Label2   0   b 
15   5   Label3   0   c 

所以我需要做的是將表單和字段組合在一起,看看它們是否完全一樣 - 即使是數據 - 這是我被困住的地方。例如表單1 & 2將被組合在一起,因爲FormName和FormType匹配,並且在字段表中FieldLabel,IsRequired和「OtherField」全部匹配。

但是,即使表單3,4都在表單表上匹配,但表單3 & 4將最終在同一個組中,因爲Fields表中的數據(OtherFields)在這些列上不相同。

的形式表(具體而言, 「組ID」 列)期望的結果:

FormID  FormName  FormType  GroupID 
---------------------------------------------- 
1   Form1  1    1 
2   Form1  1    1 
3   Form1  2    2 
4   Form2  2    2 
5   Form2  2    3 

如何才能做到這一點?我不介意使用遊標等,因爲這是一次性處理來填充新的「GroupID」列。

謝謝你們!

編輯
這裏是由Andrew創建的小提琴:http://sqlfiddle.com/#!3/3ec6f/6

+0

在該表中「表單」的所述FormID = 5和窗體名稱=窗體2的「窗體名稱」,名字簡化版,與之相匹配的結果最後一行「FormID」 = 5和「窗體名稱」 = Form5,這是一個錯誤? – GeoAvila

+0

您的意思是第一個「Forms」表與我的「期望結果」不匹配 - 是的,這是一個錯誤 - 我會爲了準確性而修復。 – Losbear

回答

1

我想這是你的想法:

;with types as (
select 
distinct formtype, 
row_number()over (order by formtype) as GroupID 
from 
(select distinct formtype from forms) t1) 


select 
f.formid, 
f.formname, 
f.formtype, 
types.GroupID 
from 
forms f 
inner join types 
on f.formtype = types.formtype 

的CTE產生組ID爲表單類型,然後你只需將它加入你的表格表。

SQL Fiddle

+0

哦,甜心,還有一個「SQL小提琴」!太好了!這幾乎是我所需要的 - 它沒有考慮到這些領域。表單之間的字段數量需要匹配以及特定的列數據(即:FieldLabel,IsRequired,OtherFields等) - 感謝Andrew。 – Losbear

+0

當然,是的。重新閱讀後,並不完全確定我瞭解你的要求與領域表。 – Andrew

+0

基本上它和你用窗體做的一樣,但是一些需要匹配的列也在Fields表中。我想知道我是否只需要添加一個INNER JOIN到cte,如果那樣做的話。 – Losbear