Sql 从左jon中排除Null
我已经加入了2个表左连接Sql 从左jon中排除Null,sql,left-join,Sql,Left Join,我已经加入了2个表左连接 Select a.Invoice, b.Prodict From table1 a left join table2 b on a.Id = b.Id 我想说的是,如果一张发票有两个或更多的产品,那么排除空值,如果只有空值,那么保持空值。 多谢各位 有福了。我认为您需要过滤第二个表,使其不包含空值 Select a.Invoice, b.Prodict From table1 a left join table2 b on a.Id =
Select a.Invoice,
b.Prodict
From table1 a
left join table2 b
on a.Id = b.Id
我想说的是,如果一张发票有两个或更多的产品,那么排除空值,如果只有空值,那么保持空值。
多谢各位
有福了。我认为您需要过滤第二个表,使其不包含空值
Select a.Invoice,
b.Prodict
From table1 a
left join table2 b
on a.Id = b.Id and b.Prodict is not null
嗯。数据中似乎有
NULL
值。我建议在左连接中过滤掉它们
本身:
Select a.Invoice,
b.Product
From table1 a left join
table2 b
on a.Id = b.Id and b.Product is not null;
唯一的NULL
s将是由左连接生成的:
此解决方案的唯一问题是,如果希望从b
中选择其他列,并且有一个匹配行NULL
。使用此解决方案,其他列将为NULL
如果这是您的实际问题,请使用示例数据和所需结果提出一个新问题。您需要确定表2中产品列中的空发票是否有任何非空行
如果您的DBMS具有分析功能,则可以使用它:
发票|产品
:------ | :------
A | AA
A | AB
B|BA
B | BB
C |空
dbfiddle使用您正在使用的数据库标记您的问题。请提供一些。如果我将产品设置为非空,则会排除一些只有空值的发票。例如,如发票号码4@Hanry_Lou不,不会的:)你们自己试试吧。请注意,筛选器处于联接条件,而不是where条件。我的表1有450M条记录,联接后返回15M条记录。很难跟踪每一行。LEFT JOIN
不会从左侧的源代码中删除任何内容,因此我无法想象它可以减少生成的行数。只要不清楚发票
、Id
和产品
之间的关系,并且没有任何DBMS标记,我就添加了这个通用答案。否则,上面有好的和简短的答案
with table1 as (
select 1 as id, 'A' as Invoice union all
select 2 as id, 'B' as Invoice union all
select 3 as id, 'B' as Invoice union all
select 4 as id, 'C' as Invoice
)
, table2 as (
select 1 as id, 'AA' as Product union all
select 1 as id, 'AB' as Product union all
select 2 as id, 'BA' as Product union all
select 2 as id, NULL as Product union all
select 2 as id, 'BB' as Product
)
, find_null as (
Select
a.Invoice,
b.Product,
/*Check if NULL is here*/
max(case when b.Product is null then 1 end) over(partition by a.Invoice) as has_null,
/*Count not null values*/
count(b.Product) over(partition by a.Invoice) as item_cnt
From table1 a
left join table2 b
on a.Id = b.Id
)
select invoice, product
from find_null
where not (
has_null = 1
and item_cnt > 0
/*Exclude null where there's a row without null*/
and product is null
)
GO
invoice | product
:------ | :------
A | AA
A | AB
B | BA
B | BB
C | null
with table1 as (
select 1 as id, 'A' as Invoice union all
select 2 as id, 'B' as Invoice union all
select 3 as id, 'B' as Invoice union all
select 4 as id, 'C' as Invoice
)
, table2 as (
select 1 as id, 'AA' as Product union all
select 1 as id, 'AB' as Product union all
select 2 as id, 'BA' as Product union all
select 2 as id, NULL as Product union all
select 2 as id, 'BB' as Product
)
Select
a.Invoice,
b.Product
From table1 a
left join table2 b
on a.Id = b.Id
where not exists (
select 1
from table1 f1
join table2 f2
on f1.id = f2.id
where f1.invoice = a.invoice
and f2.product is not null
and b.Product is null
)
GO
Invoice | Product
:------ | :------
A | AA
A | AB
B | BA
B | BB
C | null