我正在尝试使用以下语法使存储过程工作:
select count(sl.Item_Number)
as NumOccurrences
from spv3SalesDocument as sd
left outer join spv3saleslineitem as sl on sd.Sales_Doc_Type = sl.Sales_Doc_Type and
sd.Sales_Doc_Num = sl.Sales_Doc_Num
where
sd.Sales_Doc_Type='ORDER' and
sd.Sales_Doc_Num='OREQP0000170' and
sl.Item_Number = 'MCN-USF'
group by
sl.Item_Number
having count (distinct sl.Item_Number) = 0在此特定情况下,当不满足条件时,查询不返回任何记录,并且“count”为空。我需要一个返回的0,这样我就可以应用一个条件,而不是什么都不应用。
我猜这是一个相当简单的解决方法,但超出了我简单的大脑能力。
任何帮助都是非常感谢的。
沃利
发布于 2010-06-13 00:22:48
首先,在sl上有一个特定的where子句违背了左外部连接的目的--它基本上把它变成了内连接。
听起来,如果没有匹配项,您会尝试返回0。我是一名T-SQL程序员,所以我不知道这在其他方面是否有意义……我对此查询的上下文了解不多,但听起来您似乎是在尝试使用此查询在IF语句中进行分支……也许这会对你有所帮助,即使它不是你想要的……
IF NOT EXISTS (SELECT 1 FROM spv3SalesDocument as sd
INNER JOINs pv3saleslineitem as sl on sd.Sales_Doc_Type = sl.Sales_Doc_Type
and sd.Sales_Doc_Num = sl.Sales_Doc_Num
WHERE sd.Sales_Doc_Type='ORDER'
and sd.Sales_Doc_Num='OREQP0000170'
and sl.Item_Number = 'MCN-USF')
BEGIN
-- Do something...
END发布于 2010-06-13 00:20:10
我没有测试这些,但我想先试一试:
select ISNULL(count(sl.Item_Number), 0) as NumOccurrences如果那个不起作用,试试这个:
select
CASE count(sl.Item_Number)
WHEN NULL THEN 0
WHEN '' THEN 0
ELSE count(sl.Item_Number)
END as NumOccurrences发布于 2010-06-13 00:35:41
group by和having的组合看起来非常可疑:
group by sl.Item_Number
having count (distinct sl.Item_Number) = 0我希望这个having条件只允许组是Item_Number is null。
若要始终返回行,请使用union。例如:
select name, count(*) as CustomerCount
from customers
group by
name
having count(*) > 1
union all
select 'No one found!', 0
where not exists
(
select *
from customers
group by
name
having count(*) > 1
)https://stackoverflow.com/questions/3029278
复制相似问题