好的,这是我的一些代码,它给了我这个错误:
Select orderid, requireddate,
( Select DATEDIFF(dd,requireddate,shippeddate)
from sales.Orders
where shippeddate > requireddate
) as 'DaysLate'
from sales.Orders
我得到"子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。"错误。
我不太确定如何修复它,因为当我点击错误消息时它会突出显示Select orderid, requireddate
位。
我有什么不对劲吗?
答案 0 :(得分:1)
在sql下面试试
select
orderId, requiredDate
, case
when shippeddate > requireddate then DATEDIFF(dd,requireddate,shippeddate)
else
0
end as 'DaysLate'
from sales.Orders
情况..当语句可以替换子查询
答案 1 :(得分:0)
Select orderid, requireddate,
DATEDIFF(dd,requireddate,shippeddate) as 'DaysLate'
from sales.Orders
where shippeddate > requireddate
您的子查询返回多行,但对于外部查询,每列只能有一个值,因此显示错误
答案 2 :(得分:0)
您必须确保以这种方式使用的子查询返回的值不超过1。
所以至少要使用TOP 1
。像
Select orderid, requireddate,
( Select TOP 1 DATEDIFF(dd,requireddate,shippeddate)
from sales.Orders
where shippeddate > requireddate
) as 'DaysLate'
from sales.Orders
如果需要,您可能还希望在此处添加ORDER BY
。
最终,您需要弄清楚您正在寻找的值,并确保返回此单个值。
您可能还想考虑实际的orderid
。像
Select orderid, requireddate,
( Select TOP 1 DATEDIFF(dd,requireddate,shippeddate)
from sales.Orders oo
where shippeddate > requireddate
and oo.orderid = o.orderid
) as 'DaysLate'
from sales.Orders o
答案 3 :(得分:0)
Imho你在sql查询中缺少o1.orderid = o2.orderid。 这是原创方式:
Select o1.orderid, o1.requireddate,
( Select DATEDIFF(dd,o2.requireddate,o2.shippeddate)
from sales.Orders o2
where o2.shippeddate > o2.requireddate and o1.orderid = o2.orderid
) as 'DaysLate'
from sales.Orders o1
然后重写了一下:
Select o1.orderid, o1.requireddate, DL.DaysLate
from sales.Orders o1
join ( Select o2.orderid, DATEDIFF(dd,o2.requireddate,o2.shippeddate) as DaysLate
from sales.Orders o2
where o2.shippeddate > o2.requireddate
) as DL on dl.orderid = o1.orderid
您尚未描述要检索的数据的业务含义,因此请在此处使用join / left join。