数据分为多个组

时间:2014-10-31 05:33:40

标签: sql sql-server algorithm tsql sql-server-2008-r2

我想将数据分组为多个组。

例如如下所示。

示例

我有桌面测试:

create table test
(
 column1 varchar(10),
 column2 varchar(10)
)

插入一些数据:

insert into test values('X','Y');
insert into test values('Y','Z');
insert into test values('X','A');
insert into test values('O','P');
insert into test values('N','M');
insert into test values('S','T');
insert into test values('W','O');
insert into test values('A','K');
insert into test values('E','N');

现在我有这些数据:

select * from test;

column1    column2
------------------
   X         Y
   Y         Z
   X         A
   O         P
   N         M
   S         T
   W         O
   A         K
   E         N

在上面的数据中,我有必须对它们进行分组的值彼此属于:
  (X-Y,Y-Z,X-A,A-K)以及(O-P,W-O)(N-M,E-N)

对于这些值,我必须创建一个组group 1,2,3

第1组:(X-Y,Y-Z,X-A,A-K)
第2组:(O-P,W-O)
第3组:(N-M,E-N)

我想以下列格式显示表格:

结果

Group Number   column1    column2
--------------------------------
     1            X         Y
     1            Y         Z
     1            X         A
     2            O         P
     3            N         M
     0            S         T
     2            W         O
     1            A         K
     3            E         N

2 个答案:

答案 0 :(得分:2)

SELECT
    CASE (column1 + column2)
        WHEN 'XY' THEN '1'
        WHEN 'YZ' THEN '1'
        WHEN 'XA' THEN '1'
        WHEN 'AK' THEN '1'
        WHEN 'OP' THEN '2'
        WHEN 'WO' THEN '2'
        WHEN 'NM' THEN '3'
        WHEN 'EN' THEN '3'
        ELSE '0'
    END AS [Group Number],
    column1,
    column2
FROM test
--ORDER BY [Group Number]

... OR

SELECT
    CASE 
        WHEN (column1 + column2) IN ('XY', 'YZ', 'XA', 'AK') THEN '1'
        WHEN (column1 + column2) IN ('OP', 'WO') THEN '2'
        WHEN (column1 + column2) IN ('NM', 'EN') THEN '3'
        ELSE '0'
    END AS [Group Number],
    column1,
    column2
FROM test

答案 1 :(得分:0)

DECLARE @table TABLE (GroupNumber int,column1 VARCHAR(1),column2 VARCHAR(1))  
INSERT INTO @table VALUES 
(1,'X','Y'),(1,'Y','Z'),(1,'X','A'),(1,'A','K'),
(2,'O','P'),(1,'W','O'),
(3,'N','M'),(3,'E','N')

SELECT      ISNULL(LU.GroupNumber,0) GroupNumber,
            T.column1,
            T.column2
FROM        test T
LEFT JOIN   @table LU 
            ON  T.column1 = LU.column1 
            AND T.column2 = LU.column2