TSQL:对大量数据进行分组

时间:2013-11-20 15:31:17

标签: sql-server 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

所以我需要做的是将表单和字段组合在一起,看看它们是否完全相同 - 甚至数据 - 这就是我难倒的地方。例如Form 1&amp; 2将组合在一起,因为FormName和FormType匹配,并且在字段表中,FieldLabel,IsRequired和“OtherField”都匹配。

然而即使表格3,4和&amp; 5表单上的所有匹配,只有表格3和表格3 4将最终出现在同一个组中,因为Fields表中的数据(OtherFields)在这些列上不相同。

Forms表的所需结果(特别是“GroupID”列):

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”列的一次性协议。

谢谢你们!

修改
这是安德鲁创造的小提琴:http://sqlfiddle.com/#!3/3ec6f/6

1 个答案:

答案 0 :(得分: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