连接两个列记录以获取聚合的第三列

时间:2013-09-20 18:03:14

标签: sql sas

我有两列,第1列和第2列,每行有10条记录:

第1列(A,A,A,B,B,B,B,C,C,D)和第2列(1,1,2,3,3,2,1,4,4,1)

我需要使用这两列创建第三列column3, column3 =(A_1_1_2,B_3_3_2_1,C_4_4,D_1)

请帮助我如何做到这一点,我使用分组陈述和连接,但无法弄清楚如何。

3 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @T TABLE([col1] VARCHAR(1), [col2] VARCHAR(1));

INSERT INTO @T ([col1], [col2])
VALUES 
('A','1'), ('A','1'), ('A','2'), 
('B','3'), ('B','3'), ('B','2'), 
('B','1'), ('C','4'), ('C','4'), ('D','1');

DECLARE @col1 VARCHAR(1), @col2 VARCHAR(1), @CONCAT VARCHAR(MAX);

DECLARE col1_cursor CURSOR
FOR
SELECT DISTINCT col1
FROM @T;

OPEN col1_cursor;

FETCH NEXT
FROM col1_cursor
INTO @col1;


WHILE @@FETCH_STATUS = 0
BEGIN
    SET @CONCAT = ''

    DECLARE col2_cursor CURSOR
    FOR
    SELECT col2
    FROM @T
    WHERE col1 = @col1;

    OPEN col2_cursor;

    FETCH NEXT
    FROM col2_cursor
    INTO @col2;


    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF (@CONCAT = '')
        BEGIN
            SET @CONCAT = @col1 + '-' + @col2;
        END
        ELSE
        BEGIN
            SET @CONCAT = @CONCAT + '-' + @col2
        END


        FETCH NEXT
        FROM col2_cursor
        INTO @col2;
    END

    PRINT @CONCAT

    CLOSE col2_cursor;

    DEALLOCATE col2_cursor;


    FETCH NEXT
    FROM col1_cursor
    INTO @col1;

END

CLOSE col1_cursor;

DEALLOCATE col1_cursor;
GO

答案 1 :(得分:0)

我使用this previous question中找到的工作作为我的大部分答案。

CREATE TABLE MyTable (COLUMN1 char(1) NULL, COLUMN2 char(1) NULL);

INSERT INTO MyTable VALUES ('A', '1'), ('A', '1'), 
('A', '2'), ('B', '3'), ('B', '3'), ('B', '2'), 
('B', '1'), ('C', '4'), ('C', '4'), ('D', '1');

SELECT COLUMN1 + COLUMN2 AS COLUMN3
FROM(
  SELECT DISTINCT a.COLUMN1,
    (SELECT '_' + b.COLUMN2
     FROM MyTable b
     WHERE a.COLUMN1 = b.COLUMN1
     ORDER BY b.COLUMN1
     FOR XML PATH ('')) AS COLUMN2
  FROM MyTable a
  )c

demo

希望这可以帮助您修改查询以满足您的需求。

另外,这种方法可以避免可怕的光标。

答案 2 :(得分:0)

你走了。您需要保留第3列,并仅在每个Col1组的最后一次观察时输出:

data test;
input Col1 $ Col2;
datalines;
A 1
A 1
A 2
B 3
B 3
B 2
B 1
C 4
C 4
D 1
;;
run;

data test_out;
set test;
by Col1;
format Col3 $64.;
retain Col3;
if first.Col1 then
    Col3 = strip(Col1);

Col3 = catx("_",col3,col2);

if last.Col1 then
    output;
run;