2017-08-26 50 views
0

我需要帮助查找和分类每个不同密钥的序列模式。查找和分类不同组的序列模式T-SQL

从我所拥有的数据中,我需要创建一个新表,其中包含属于该键的键和模式标识符。

从图案下面的例子是如下:

项#1和#3的值分别为1,2和3的关键#3具有8值, 9和10中。当一键IE一个上不同的图案存在(1,2,3)I 需要创建密钥#和上表中的条目的具体 模式(1,2,3)

数据:

key   value 
1   1 
1   2 
1   3 
2   8 
2   9 
2   10 
3   1 
3   2 
3   3 

预期输出:

key   pattern 
1   1 
2   2 
3   1 

小提琴: http://sqlfiddle.com/#!6/4fe39

示例表:

CREATE TABLE yourtable 
    ([key] int, [value] int) 
; 

INSERT INTO yourtable 
    ([key], [value]) 
VALUES 
    (1, 1), 
    (1, 2), 
    (1, 3), 
    (2, 8), 
    (2, 9), 
    (2, 10), 
    (3, 1), 
    (3, 2), 
    (3, 3) 
; 
+2

请描述逻辑为“模式标识符”。这并不明显。 –

+0

密钥#1和#3的值为1,2和3.密钥#3的值为8,9和10.当独特模式存在IE(1,2,3)时,我需要在表#键和那个特定的模式 – barracuda

回答

1

您可以通过多种方式串联的值加在一起。在SQL Server中的传统方法使用for xml

select k.key, 
     stuff((select ',' + cast(t.id as varchar(255)) 
       from t 
       where k.key = t.key 
       for xml path ('') 
       order by t.id 
      ), 1, 1, '' 
      ) as ids 
from (select distinct key from t) k; 

您可以将此转换为一个使用CTE /子查询的唯一号码:

with cte as (
     select k.key, 
      stuff((select ',' + cast(t.id as varchar(255)) 
        from t 
        where k.key = t.key 
        for xml path ('') 
        order by t.id 
        ), 1, 1, '' 
       ) as ids 
     from (select distinct key from t) k 
    ) 
select cte.*, dense_rank() over (order by ids) as ids_id 
from cte; 
+0

你的CTE /子查询是解决方案,但它最初并没有在我的小提琴上工作。 下面的小提琴链接包含工作解决方案,感谢您的帮助! http://sqlfiddle.com/#!6/9fb6e/17 – barracuda