计算所有,即使是零

时间:2015-09-25 16:01:10

标签: sql

我有这个SQL

SELECT count(*) AS TotalOrders, [Sell-to Customer No_], [Document Date] 
FROM [Navision4].[dbo].[3S Company A_S$Sales Invoice Header]  
  INNER JOIN [Navision4].[dbo].[3s Statusboard Customer]
    ON [Navision4].[dbo].[3S Company A_S$Sales Invoice Header].[Sell-to Customer No_] = [Navision4].[dbo].[3s Statusboard Customer].[No_] 
WHERE [Document Date] <= '2015-09-25'
GROUP BY [Sell-to Customer No_], [Document Date]

但这不是我想做的事。

示例:

如果我在[Navision4]中有3个项目。[dbo]。[3s Statusboard Customer]。[No _]

[No_]   
10
20
30

但在我的表[Navision4]。[dbo]。[3S公司A_S $销售发票标题]仅为客户10和20的记录。

我没有客户30的记录,这将不会被退回。 但我希望我的SQL为客户30返回0而不是隐藏它。

我该怎么做?

希望我有意义:))

2 个答案:

答案 0 :(得分:4)

您似乎正在尝试计算每天客户的发票数量。如果客户没有任何发票,那么您需要进行左连接,将发票表加入到客户表中,如下所示:http://sqlfiddle.com/#!6/d7cb3a/6。如果是空日期,请选择0,否则计算(*)。

select customer.id, invoice.dt,
case when invoice.dt is null then 0 else count(*) end as TotalOrders
from customer
left join invoice
on invoice.customer = customer.id
and invoice.dt <= '2015-09-25'
group by customer.id, invoice.dt

如果您正在尝试查找客户的发票总数,请从select语句和group by子句中取出日期,如下所示:http://sqlfiddle.com/#!6/d7cb3a/11

select customer.id,
case when invoice.customer is null then 0 else count(*) end as TotalOrders
from customer
left join invoice
on invoice.customer = customer.id
and invoice.dt <= '2015-09-25'
group by customer.id, invoice.customer
order by customer.id

请注意,我在group by子句中包含了invoice.customer,因此您可以检查该字段是否为NULL。

我假设您可以将我的示例表名称转换回数据库结构。

答案 1 :(得分:0)

您需要外部联接。如果Document Date在客户表中:

SELECT count(*) AS TotalOrders, c.[No_], [Document Date] 
FROM [Navision4].[dbo].[3s Statusboard Customer] c LEFT JOIN
     [Navision4].[dbo].[3S Company A_S$Sales Invoice Header] s
     ON s.[Sell-to Customer No_] = c.[No_] 
WHERE c.[Document Date] <= '2015-09-25'
GROUP BY c.[No_], [Document Date] ;

否则,您需要将条件移至ON子句:

SELECT count(*) AS TotalOrders, c.[No_], [Document Date] 
FROM [Navision4].[dbo].[3s Statusboard Customer] c LEFT JOIN
     [Navision4].[dbo].[3S Company A_S$Sales Invoice Header] s
     ON s.[Sell-to Customer No_] = c.[No_] AND
        s.[Document Date] <= '2015-09-25'
GROUP BY c.[No_], [Document Date] ;

请注意,表别名使查询更容易编写和读取。