一招:SQL select和mach

时间:2016-05-12 19:19:47

标签: sql

我有2张这样的表:

a x1 1

b y2 2

x1 0

x2 0

x3 0

x4 0

y1 0

y2 0

y3 0

, 我希望有这张桌子:

a x1 1

a x2 0

a x3 0

a x4 0

b y1 1 

b y2 0

b y3 0

任何人都知道该怎么做?非常感谢!

2 个答案:

答案 0 :(得分:0)

在编辑前回答原始问题。

您需要CROSS JOIN

示例数据:

CREATE TABLE #Table1(Col1 VARCHAR(10)
                , Col2 VARCHAR(10), );

INSERT INTO #Table1
VALUES
      ('a'
     , 'x1'),
      ('b'
     , 'x4');

CREATE TABLE #Table2(Col1 VARCHAR(10));

INSERT INTO #Table2
VALUES
      ('x1'),
      ('x2'),
      ('x3'),
      ('x4');

QUERY:

SELECT A.Col1
    , B.Col1
FROM   #Table1 AS A
      CROSS JOIN #Table2 AS B;

结果:

enter image description here

在对问题进行编辑后,这将产生您需要的结果:

示例数据:

CREATE TABLE #Table1(Col1 VARCHAR(10)
                , Col2 VARCHAR(10)
                , Col3 INT);

INSERT INTO #Table1
VALUES
      ('a'
     , 'x1'
     , 1),
      ('b'
     , 'x4'
     , 2);

CREATE TABLE #Table2(Col1 VARCHAR(10)
                , Col2 INT);

INSERT INTO #Table2
VALUES
      ('x1'
     , 0),
      ('x2'
     , 0),
      ('x3'
     , 0),
      ('x4'
     , 0),
      ('y1'
     , 0),
      ('y2'
     , 0),
      ('y3'
     , 0);

QUERY:

SELECT A.Col1
    , B.Col1
    , CASE
         WHEN B.Col1 LIKE '%1' THEN 1
         ELSE B.Col2
      END
FROM   #Table1 AS A
      CROSS JOIN #Table2 AS B
WHERE  (A.Col1 = 'a'
       AND B.Col1 LIKE 'x%'
      )
      OR (A.Col1 = 'b'
         AND B.Col1 LIKE 'y%'
        );

结果:

enter image description here

请注意,您需要小心使用CROSS JOINS,因为它可能导致大量结果集

答案 1 :(得分:0)

不确定你要做什么,但似乎你必须要子串以便在两个表之间加入。我不知道第三列的来源;看起来你正把它设置为" 1"每次小组(col1)改变。

with t1(col1, col2, col3)
as (
select 'a','x1',1 from dual union all 
select 'b','y2',2 from dual
),
 t2(col1,col2)
as (
select 'x1',0 from dual union all
select 'x2',0 from dual union all
select 'x3',0 from dual union all
select 'x4',0 from dual union all
select 'y1',0 from dual union all
select 'y2',0 from dual union all
select 'y3',0 from dual 

)

select  t1.col1, t2.col1, 
        case when row_number() over (partition by t1.col1 order by rownum) > 1 
             then 0 
             else 1
        end col3
from t2 join t1
on substr(t1.col2,1,1) = substr(t2.col1,1,1)
order by 1, 2