【问题标题】:Is there a way to return 0 if values does not exist in table using SQL Server如果使用 SQL Server 的表中不存在值,有没有办法返回 0
【发布时间】:2020-11-14 08:56:47
【问题描述】:

我在下面写了一个查询以从四个表中检索

Sales_Invoice, New_Customer, Company_Information, Expense

查询:

select
    isnull(sum(Expense.Expense_Amount), 0.00), as ExpenseAmount, 
    Company_Information.Company_Name,
    Sales_Invoice.Invoice_No, Sales_Invoice.Invoice_Date, Sales_Invoice.Item_Name,
    New_Customer.Customer_Name, New_Customer.Customer_ID
from 
    Sales_invoice, Company_Information, New_Customer, Expense
where 
    Sales_Invoice.Customer_Id = New_Customer.Customer_ID 
    and Sales_Invoice.Invoice_No = Expense.Invoice_No
group by
    Company_Information.Company_Name,
    Sales_Invoice.Invoice_No, Sales_Invoice.Invoice_Date, Sales_Invoice.Customer_ID, 
    Sales_Invoice.Item_Name, New_Customer.Customer_Name, New_Customer.Customer_ID 

查询运行良好,但如果Expense 表没有值Expense.Invoice_NoSales_Invoice.Invoice_No 不匹配,则上面的查询将返回空行。

但我想做的是,如果Expense.Invoice_No 不存在,那么我仍然希望我的行提供该费用金额返回 0.00

【问题讨论】:

  • 对于这个问题,我会将“上面的查询运行良好”的情绪更改为“它执行”,或者其他类似的东西;因为,如果连接没有产生您期望的结果,则查询不会“正常工作”。另外,上面的代码 sn -p , as ExpenseAmount 似乎是错误的。
  • @Brett Caswell 如果我将某些内容保存在费用表中,则上面的查询有效,但如果我没有保存,我希望它返回 null
  • 很久以前你就不再使用那个古老的连接语法了;它在 27 年前被取代!
  • Bad Habits to Kick : Using old-style JOINs。如果您切换到正确的LEFT JOIN,很可能您可以实现您的目标
  • 您的隐式连接中也缺少Company_Information;转向正确的连接语法的另一个原因。

标签: c# sql sql-server sum left-join


【解决方案1】:

使用标准连接!然后,您可以使用left join 轻松处理“缺失”关系。

你的问题提示:

select
    coalesce(sum(e.expense_amount), 0.00) as expenseamount, 
    ci.company_name,
    si.invoice_no, si.invoice_date, si.item_name,
    nc.customer_name, nc.customer_id
from new_customer nc
inner join company_information ci on ???
inner join sales_invoice si       on si.customer_id = nc.customer_id 
left join expense e               on e.invoice_no = si.invoice_no
group by
    ci.company_name,
    si.invoice_no, si.invoice_date, si.customer_id, 
    si.item_name, nc.customer_name, nc.customer_id 

请注意,您的原始代码在我看来缺少客户和公司之间的连接条件。我在查询中将其表示为???

您也可以使用相关子查询来表达相同的逻辑,这将避免外部聚合:

select
    (
        select coalesce(sum(e.expense_amount), 0.00) 
        from expense e 
        where e.invoice_no = si.invoice_no
    ) as expenseamount, 
    ci.company_name,
    si.invoice_no, si.invoice_date, si.item_name,
    nc.customer_name, nc.customer_id
from new_customer nc
inner join company_information ci on ???
inner join sales_invoice si on si.customer_id = nc.customer_id 

【讨论】:

  • 公司信息没有任何ID参考,我只是想用那些表来检索它
  • @Temitayo:所以公司和其他表之间根本没有关系?这有点令人惊讶,但在这种情况下你会这样做:from new_customer nc cross join company_information ci inner join sales_invoices ...。如果公司表中有不止一行,这将增加行数。
  • @Temitayo:没有看到您的实际数据,很难提出建议。也许您也有没有销售的客户(不仅没有费用)?在这种情况下,将另一个内连接也更改为左连接。
  • 我把这个小提琴放在一起,但在我完成之前看到了这个答案..随时检查一下并玩一下。 sqlfiddle.com/#!18/c18a1/3
猜你喜欢
  • 2018-10-22
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 1970-01-01
相关资源
最近更新 更多