我有以下SQL:
DECLARE @ActualFromDT DATETIME,
@ActualToDT DATETIME
IF (ManPowerUsage.FromDT >= Shift.FromDT)
SET @ActualFromDT = ManPowerUsage.FromDT
ELSE
SET @ActualFromDT = Shift.FromDT
IF (ManPowerUsage.ToDT <= Shift.ToDT)
SET @ActualToDT = ManPowerUsage.ToDT
ELSE
SET @ActualToDT = Shift.ToDT
SELECT Shift.ShiftID,
Line.Line,
( SELECT SUM(DATEDIFF(MINUTE, @ActualFromDT, @ActualToDT))
/ DATEDIFF(MINUTE, Shift.FromDT, Shift.ToDT)
FROM ManPowerUsage
WHERE ManPowerUsage.LineID = Line.LineID
AND ((Shift.FromDT < ManPowerUsage.FromDT AND Shift.ToDT > ManPowerUsage.FromDT)
OR (Shift.FromDT < ManPowerUsage.ToDT AND Shift.ToDT > ManPowerUsage.ToDT ))
AND ManPowerUsage.IsEdited = 0
) AS ActualManpower
FROM ......
该命令显然不起作用,但我想知道如何在执行DATEDIFF
之前设置参数
答案 0 :(得分:2)
无处。您使用CASE expression作为“内联IF”
SELECT Shift.ShiftID,
Line.Line,
( SELECT SUM(DATEDIFF(MINUTE,
CASE
WHEN ManPowerUsage.FromDT >= Shift.FromDT
THEN ManPowerUsage.FromDT
ELSE Shift.FromDT
END,
CASE
WHEN ManPowerUsage.ToDT <= Shift.ToDT
THEN ManPowerUsage.ToDT
ELSE Shift.ToDT
END))
/ DATEDIFF(MINUTE, Shift.FromDT, Shift.ToDT)
...
答案 1 :(得分:0)
你不应该需要任何变量,这样的事情就可以了。虽然没有完整的模式样本,SQL片段是不可测试的。
SELECT
Shift.ShiftID,
Line.Line,
( SELECT SUM
(
DATEDIFF
(
MINUTE,
case when mpu.FromDT>Shift.FromDt then mpu.FromDT else Shift.FromDt end,
case when mpu.ToDT<=Shift.ToDt then mpu.ToDT else Shift.ToDt end
)
)
/ DATEDIFF(MINUTE, Shift.FromDT, Shift.ToDT)
FROM ManPowerUsage mpu
WHERE mpu.LineID = Line.LineID
AND (
( Shift.FromDT < mpu.FromDT
AND Shift.ToDT > mpu.FromDT
)
OR ( Shift.FromDT < mpu.ToDT
AND Shift.ToDT > mpu.ToDT
)
)
AND mpu.IsEdited = 0
) AS ActualManpower
FROM ......