A有一个SQL Server语句,用于计算计划的总时间长度,总计超过总计。我想要包含一个if / case语句,如果另一个单元格为空,我将允许多个时间表的长度为2,否则保持不变。
我目前有:
SELECT
SUM(ScheduledDuration) AS TotalScheduleDuration,
SUM(FirstCarerDuration) AS TotalCareDuration,
COUNT(NumberOfRows) AS NumberOfRows,
SUM(NumberOfCarers) AS NumberOfCarers
FROM
(SELECT
@@ROWCOUNT AS NumberOfRows,
CASE
WHEN SecondCarerID = '' THEN 1
ELSE 2
END as NumberOfCarers,
(DateDiff(MI, StartTime, EndTime)) * (NumberOfCarers) as ScheduledDuration,
DateDiff(MI, SignIn, SignOut) as FirstCarerDuration,
DateDiff(MI, SecondSignIn, SecondSignOut) as SecondCarerDuration,
(DateDiff(MI, SignIn, SignOut)) + isnull(DateDiff(MI, SecondSignIn, SecondSignOut),0) as CareDuration
FROM
tblSchedules
WHERE
SignIn != 'M'
AND SignOut != 'M'
AND ProviderID = 123
AND DateOfCare = '2016/01/09') DT
我正在使用案例将乘数值设置为NumberOfCarers
,但我收到错误消息:
无效的列名称NumberOfCarers
如何通过case语句的结果复用ScheduleDuration
?
其他则不会将查询的其余部分相乘。
谢谢,
约什
答案 0 :(得分:1)
要解决此问题,您需要复制表达式或嵌套查询,以便您可以通过别名引用其列。既然你已经有了一个嵌套我认为最直接的解决方法就是在求和中进行乘法运算。
SELECT
SUM(ScheduledDuration * NumberOfCarers) AS TotalScheduleDuration,
SUM(FirstCarerDuration) AS TotalCareDuration,
COUNT(*) AS NumberOfRows, --COUNT(NumberOfRows) AS NumberOfRows,
SUM(NumberOfCarers) AS NumberOfCarers
FROM
(
SELECT
--@@ROWCOUNT AS NumberOfRows,
CASE WHEN SecondCarerID = '' THEN 1 ELSE 2 END as NumberOfCarers,
DateDiff(MI, StartTime, EndTime) as ScheduledDuration,
DateDiff(MI, SignIn, SignOut) as FirstCarerDuration,
DateDiff(MI, SecondSignIn, SecondSignOut) as SecondCarerDuration,
DateDiff(MI, SignIn, SignOut)
+ isnull(DateDiff(MI, SecondSignIn, SecondSignOut), 0) as CareDuration
FROM tblSchedules
WHERE
SignIn != 'M' AND SignOut != 'M'
AND ProviderID = 123 AND DateOfCare = '2016/01/09'
) DT
顺便说一句@@rowcount
将是先前执行的查询的结果。我认为你只想count(*)
而不是count(NumberOfRows)