我有两列,column1 和 2,每列有 10 条记录,例如:
Column1 (A, A, A, B, B, B, B, C, C, D) 和 Column2 (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)
请帮助我如何做到这一点,我正在使用 group by 语句和 concatinations 但无法弄清楚如何。
尝试这个:
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
干得好。您需要保留第 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;
我的大部分答案都使用了在上一个问题中找到的工作。
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
希望这能让您达到可以修改查询以满足您的需求的程度。
另外,这种方法能够避免可怕的光标。