INSERT INTO @trAll
SELECT tr.EventDateTime
,tr.OrderId
,'EX'
,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR,0)
,tr.eAD
,tr.OperatorName
--
,cmr.ConsigneeName
,cmr.ConsigneeCompanyCode
,cmr.SenderName
,cmr.SenderCompanyCode
FROM vwTransaction AS tr
inner join tbOrderDetailCMR as cmr
on tr.orderid = cmr.OrderId
WHERE tr.EventDateTime BETWEEN @From
AND @to
AND ProductName = 'BIODIESELZ'
这就是我所需要的(希望你能理解我的意思):
INSERT INTO @trAll
SELECT tr.EventDateTime
,tr.OrderId
,'EX'
,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR+ (if (tr.Prod01_AdditiveA>0) THEN tr.Prod01_AdditiveA ELSE tr.Prod01_AdditiveB),0)
,tr.eAD
,tr.OperatorName
--
,cmr.ConsigneeName
,cmr.ConsigneeCompanyCode
,cmr.SenderName
,cmr.SenderCompanyCode
FROM vwTransaction AS tr
inner join tbOrderDetailCMR as cmr
on tr.orderid = cmr.OrderId
WHERE tr.EventDateTime BETWEEN @From
AND @to
AND ProductName = 'BIODIESELZ'
简而言之,我需要的是添加AdditiveA,如果它的值大于0,否则AdditiveB在select语句中。
答案 0 :(得分:4)
根据您使用的语法我假设这是T-SQL(Microsoft SQL-Server):
你不能在这样的声明中使用IF
。在这里使用CASE
,如下所示:
...
,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR+
(CASE
WHEN (tr.Prod01_AdditiveA>0) THEN tr.Prod01_AdditiveA
ELSE tr.Prod01_AdditiveB
END),0)
...
编辑:事实上,现在我读了它,Ashwin Nairs的回答甚至更好。他使用IIF
命令,该命令较少"侵入"。你可能想看看和/或接受他的答案。
答案 1 :(得分:3)
假设您正在使用sql-server,请尝试使用iif
代替
INSERT INTO @trAll
SELECT tr.EventDateTime
,tr.OrderId
,'EX'
,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR+ iif(tr.Prod01_AdditiveA>0, tr.Prod01_AdditiveA, tr.Prod01_AdditiveB),0)
,tr.eAD
,tr.OperatorName
--
,cmr.ConsigneeName
,cmr.ConsigneeCompanyCode
,cmr.SenderName
,cmr.SenderCompanyCode
FROM vwTransaction AS tr
inner join tbOrderDetailCMR as cmr
on tr.orderid = cmr.OrderId
WHERE tr.EventDateTime BETWEEN @From
AND @to
AND ProductName = 'BIODIESELZ'