SQL语句

时间:2018-03-16 06:50:17

标签: sql sql-server

我正在使用SQL生成报告。我有一个除以零的错误。要解决此错误,我在SQL查询中使用了大小写。现在我在'as'处收到语法错误。有没有人可以帮我解决这个问题?

create procedure dbo.CompanyAverageSales @startdate as varchar(50),@enddate 
as varchar(50)
As begin

select  datename(year,SO_SalesOrder.InvoicedDate) as [Year],
    datename(month,SO_SalesOrder.InvoicedDate) as [Month],
    l.Name as [Store Name], 
    case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as [Average Sales]
From SO_SalesOrder
inner join BASE_Location l on SO_SalesOrder.LocationId = l.LocationId 
inner join SO_SalesOrder_Line
on SO_SalesOrder.SalesOrderId = SO_SalesOrder_Line.SalesOrderId
inner join BASE_PaymentTerms
on BASE_PaymentTerms.PaymentTermsId = SO_SalesOrder.PaymentTermsId
where SO_SalesOrder.InvoicedDate >= @startdate and SO_SalesOrder.InvoicedDate <= @enddate
group by l.Name,
         datename(year,SO_SalesOrder.InvoicedDate),
         datename(month,SO_SalesOrder.InvoicedDate)


end

5 个答案:

答案 0 :(得分:5)

END

之前添加AS
case 
when sum(convert(int,SO_SalesOrder.Custom1))>0 
then 
    sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) 
Else 
    0
END as [Average Sales]

答案 1 :(得分:2)

case when sum(convert(int,SO_SalesOrder.Custom1))>0 then 
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as 
[Average Sales

应该是:

 case when sum(convert(int,SO_SalesOrder.Custom1))>0 then 
 sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) 
 ELSE 0 -- your logic here
 END as [Average Sales

答案 2 :(得分:2)

在这种情况下避免除零的一个好方法是使用NULLIF

sum(SO_SalesOrder_Line.SubTotal) 
/ 
NULLIF(sum(convert(int,SO_SalesOrder.Custom1)), 0)

如果NULL

,这将返回sum(convert(int,SO_SalesOrder.Custom1)) = 0

如果您想返回0,那么您可以将表达式包装在COALESCE中:

COALESCE(sum(SO_SalesOrder_Line.SubTotal) 
         / 
         NULLIF(sum(convert(int,SO_SalesOrder.Custom1)), 0), 0)

答案 3 :(得分:0)

select
    sum(SO_SalesOrder_Line.SubTotal)/NULLIF(sum(convert(int,SO_SalesOrder.Custom1)),0)
FROM ...

对于结果为零除

的记录,这将返回Null

答案 4 :(得分:0)

此行生成错误:

df=spark.read.orc([path1,path2])

您应该使用case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as [Average Sales] 关闭case语句:

end