1

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

我正在寻找一种通用解决方案,它可以处理#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。

4

3 回答 3

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
于 2008-10-21T08:15:04.390 回答
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
于 2008-10-20T23:22:02.173 回答
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 ,同样

于 2008-10-21T06:46:10.123 回答