在SQL中拆分行

时间:2008-10-20 22:21:11

标签: sql rows split

有人可以让我知道如何使用SQL以不同的方式获取三行的不同部分吗? #t2中的三行表示集合A,B,C - 我正在寻找AIB,AIC,BIC,AIBIC,A',B',C'等(7个可能的段,其中3行,如维恩图中所示)在哪里我是交叉路口。

我正在寻找一种通用解决方案,它可以处理#t2中的n行。

-- SQL Code Begin
create table #t1 (key1 int, key2 int) -- for each Key1 there can be 1 or more Key2
go
create table #t2 (row_id int identity(101, 1), key1 int) --row_id is the primary key
go 

insert into #t1
select 1, 11 union select 1, 12 union select 1, 13 union select 1, 14 union 
select 2, 13 union select 2, 15 union select 2, 16 union select 2, 17 union 
select 3, 13 union select 3, 12 union select 3, 16 union select 3, 17

-- 1 --> 11, 12, 13, 14
-- 2 --> 13, 15, 16, 17
-- 3 --> 13, 12, 16, 17

insert into #t2 (key1)
select 1 union select 2 union select 3

-- SQL Code End

我正在寻找的输出是,

1001  11 (A')
1001  14 (A')
1002  12 (A I C - A I B I C)
1003  13 (A I B I C)
1004  15 (B')
1005  16 (B I C - A I B I C)
1005  17 (B I C - A I B I C)

输出有5个段,而不是可能的7个,因为其中两个是NULL。

3 个答案:

答案 0 :(得分:3)

如果我已正确理解问题,我认为您可能不得不求助于使用循环来处理'n'行数

DECLARE @Key2 INT
DECLARE @Subset VARCHAR(1000)
DECLARE @tblResults TABLE
(
    Key2 INT,
    Subset VARCHAR(1000)
)

SET @Subset = ''
SELECT @Key2 = MIN(Key2) FROM #t1

WHILE @Key2 IS NOT NULL
BEGIN
    SELECT @Subset = @Subset + CAST(Key1 AS VARCHAR(10))
    FROM #t1
    WHERE Key2 = @Key2

    INSERT INTO @tblResults (Key2, Subset)
    VALUES (@Key2, @Subset)

    SET @Subset = ''
    SELECT @Key2 = MIN(Key2) FROM #t1 WHERE Key2 > @Key2
END

SELECT * FROM @tblResults

答案 1 :(得分:0)

这个怎么样?

SELECT key2,
  CASE
  WHEN InA = 1 and InB = 1 and InC = 1 THEN 'ABC'
  WHEN InA = 0 and InB = 1 and InC = 1 THEN 'BC'
  WHEN InA = 1 and InB = 0 and InC = 1 THEN 'AC'
  WHEN InA = 1 and InB = 1 and InC = 0 THEN 'AB'
  WHEN InA = 1 and InB = 0 and InC = 0 THEN 'A'
  WHEN InA = 0 and InB = 1 and InC = 0 THEN 'B'
  WHEN InA = 0 and InB = 0 and InC = 1 THEN 'C'
  ELSE 'I''m broke'
  END as [SubSet]
FROM

(
SELECT key2,
  MAX(CASE WHEN key1 = 1 THEN 1 ELSE 0 END) as InA,
  MAX(CASE WHEN key1 = 2 THEN 1 ELSE 0 END) as InB,
  MAX(CASE WHEN key1 = 3 THEN 1 ELSE 0 END) as InC
FROM #t1
WHERE key1 in (1, 2, 3)
GROUP BY key2
) sub

ORDER BY key2

答案 2 :(得分:0)

如果您可以将表2弹出

1, Key1-Value 1
2, Key1-Value 2
4, Key1-Value 3

同样,如果你有更多的key1,那么你应该将身份列填充为二叉树。 这样t2中的值就是

1 , 1
2 , 2
4 , 3

然后你需要做一个选择:

select sum(identity), key2
from t1, t2
where t1.key1 = t2.key1
groupby key2

您将获得的输出

1   11
5   12
7   13
1   14
2   15
6   16
6   17

你可以看到1,2,4将是A',B',C'2将是A | B,7将是A | B | C同样