如果查询返回空行,我需要将其获取为零值,如何在Sql中对其进行检查?

时间:2019-02-06 10:43:19

标签: sql

Update TABLE_A
Set  TABLE_A.Form_8 =(Case When TABLE_B.Form_Type ='8' Then  TABLE_B. Invoice_NO End)
From TABLE_A
Inner Join (Select Max(Invoice_NO) as Invoice_NO,Form_Type, Counter_Name From Sales_Master
Group By Counter_Name,Form_Type
) TABLE_B on  TABLE_A.Counter_Name = TABLE_B.Counter_Name and 

TABLE_B.Form_Type ='8'

在查询的“内部联接”下方,预期输出为空, 但是实际上我想将Invoice_No设置为0

Select Max(Invoice_NO) as Invoice_NO,Form_Type, Counter_Name 
From Sales_Master
Group By Counter_Name,Form_Type

image

4 个答案:

答案 0 :(得分:2)

我怀疑您最好的选择是使用LEFT OUTER联接而不是INNER JOIN,并使用ISNULLLEFT OUTER意味着即使该行与任何内容都不匹配,您都将保留该行,而ISNULL则允许您选择在该情况下要使用的值;所以:

Update TABLE_A
Set  TABLE_A.Form_8 =(Case When TABLE_B.Form_Type ='8' Then  ISNULL(TABLE_B.Invoice_NO, 0) End)
From TABLE_A
Left Outer Join (Select Max(Invoice_NO) as Invoice_NO,Form_Type, Counter_Name From Sales_Master
Group By Counter_Name,Form_Type
) TABLE_B on  TABLE_A.Counter_Name = TABLE_B.Counter_Name and 

TABLE_B.Form_Type ='8'

答案 1 :(得分:0)

您可以使用case语句,这将适用于许多不同的提供程序。

这是您的方法。

Update TABLE_A
Set  TABLE_A.Form_8 =(Case When TABLE_B.Form_Type ='8' Then 
(case when TABLE_B.Invoice_NO is null then 0 else TABLE_B. Invoice_NO end) End)
From TABLE_A
Inner Join (Select Max(Invoice_NO) as Invoice_NO,Form_Type, Counter_Name From Sales_Master
Group By Counter_Name,Form_Type
) TABLE_B on  TABLE_A.Counter_Name = TABLE_B.Counter_Name and 

TABLE_B.Form_Type ='8'

答案 2 :(得分:0)

我怀疑您想要表格类型8的最大发票号。如果是这样,则需要在子查询中 进行过滤。

要分配所有值,只需使用LEFT JOIN

update a
    set a.Form_8 = sm.Invoice_NO
from table a left join
     (select Counter_Name, Max(Invoice_NO) as Invoice_NO
      from Sales_Master sm
      where sm.Form_Type ='8'
      group by Counter_Name
     ) sm
     on a.Counter_Name = sm.Counter_Name;

答案 3 :(得分:-1)

尝试在SQL Server中使用ISNULL

Select ISNULL(Max(Invoice_NO),0) as Invoice_NO,Form_Type, Counter_Name 
From Sales_Master
Group By Counter_Name,Form_Type