簡體   English   中英

TSQL:分組大量數據

[英]TSQL: Grouping LARGE amounts of data

我有一個正在處理的項目,要求對如下所示的記錄進行分組,並且需要一些幫助...

這是當前的結構:

表格: 表格

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

所以我要做的是將“表單”和“字段”組合在一起,看看它們是否完全相同-甚至是DATA-這也是我很困惑的地方。 例如,將表單1和2分組在一起,因為FormName和FormType匹配,並且在字段表中,FieldLabel,IsRequired和“ OtherField”都匹配。

但是,即使窗體3、4和5在窗體表上都匹配,但只有窗體3和4會以同一組結尾,因為“字段”表中的數據(其他字段)在那些列上是不同的。

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”列。

多謝你們!

編輯
這是安德魯(Andrew)創建的小提琴: http : //sqlfiddle.com/#!3/3ec6f/6

我認為這是您要記住的:

;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小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM