2

我需要从 2 个表创建一个视图。它们由一列链接,但在一个表中,此列是主键,在另一个表中,此列可以有重复项。生成的视图不应有此列的重复项。如果第二个表中的一行满足 CASE 条件,则视图中的结果应为“Y”,而不管同一键的其他行。

请查看脚本和加入结果。 结果第一行不正确,应该淘汰

Create table A1Table(
    a Integer not null
);

Create table A2Table(
    a Integer,
    b Integer
);

insert into A1Table values (1);
insert into A1Table values (2);
insert into A1Table values (3);
insert into A2Table values (1, 1);
insert into A2Table values (1, 100);

CREATE VIEW A12 AS select a1.a,
CASE
    WHEN a2.b=100 AND a2.b is not NULL THEN 'Y'
    ELSE 'N'
END AS report
FROM A1Table a1
Left JOIN A2Table a2 ON a2.a = a1.a;

-->

   a | report
  ---+--------
 **1 | N** -> *should be eliminated*
   1 | Y
   2 | N
   3 | N
4

2 回答 2

2

将条件放在a2.bJOIN 条件中。

SELECT a1.a,
       IF(a2.b IS NOT NULL, "Y", "N") report
FROM A1Table a1
LEFT JOIN A2Table a2 ON a1.a = a2.a AND a2.b = 100

我假设该组合a, bA2Table. 如果您可以有重复的组合,那么您需要使用子查询DISTINCT

SELECT a1.a,
       IF(a2.b IS NOT NULL, "Y", "N") report
FROM A1Table a1
LEFT JOIN (SELECT DISTINCT a, b
           FROM A2Table
           WHERE b = 100) a2 ON a1.a = a2.a
于 2013-05-09T16:58:59.810 回答
0

由于Y大于N,您可以:

select  a
,       max(report) as NoDuplicateReport
from    (
        select  a1.a
        ,       CASE
                WHEN a2.b=100 AND a2.b is not NULL THEN 'Y'
                ELSE 'N'
                END AS report
        FROM    A1Table a1
        LEFT JOIN 
                A2Table a2 
        ON      a2.a = a1.a
        ) SubQueryAlias
group by
        a
于 2013-05-09T16:47:30.770 回答