0

我有一张这样的桌子:

a1   b1
a1   b2
a2   b2
a2   b3

我想做一个“虚拟行”来得到这样的结果:

a1   b1   1
a1   b2   1
a1   b3   0
a2   b1   0
a2   b2   1
a2   b3   1

我已经完成了 JOIN,但它需要太长时间,因为我的表中有 140 万行,有人有更好的主意吗?

4

1 回答 1

0

这是一种使用 SQL Server 语法的方法

DECLARE @dummyTable TABLE(aValue VARCHAR(10),bValue VARCHAR(10));
INSERT INTO @dummyTable VALUES
 ('a1','b1')
,('a1','b2')
,('a2','b2')
,('a2','b3');

WITH DistinctA AS
(SELECT DISTINCT aValue FROM @dummyTable)
,DistinctB AS
(SELECT DISTINCT bValue FROM @dummyTable)
SELECT a.aValue
      ,b.bValue
      ,CASE WHEN EXISTS(SELECT 1 
                        FROM @dummyTable AS dt 
                        WHERE dt.aValue=a.aValue AND dt.bValue=b.bValue) THEN 1 ELSE 0 END AS Existing 
FROM DistinctA AS a
CROSS JOIN DistinctB AS b
ORDER BY a.aValue,b.bValue
于 2016-06-08T20:06:28.127 回答