我正在尝试从多个子查询中得出结果的总和。 我有许多定义有两个变量的时期:
declare
@left1 date = '2014-06-25',
@return1 date ='2014-08-21',
@left2 date = '2014-10-29',
@return2 date = '2015-03-15',
@left3 date = '2015-04-21',
@return3 date = '2015-09-19'
然后我正在计算这两个日期之间的日期,但最终我想将它们加起来并得到总计:
select datediff(day, @left1, @return1 )
select datediff(day, @left2, @return2 )
select datediff(day, @left3, @return3 )
我想到了CTE,但没有成功。正确的方法是什么?
答案 0 :(得分:4)
很确定您只需要一些基本的补充。
select datediff(day, @left1, @return1 )
+ datediff(day, @left2, @return2 )
+ datediff(day, @left3, @return3 )
答案 1 :(得分:3)
select
datediff(day, @left1, @return1 ) +
datediff(day, @left2, @return2 ) +
datediff(day, @left3, @return3 )
答案 2 :(得分:2)
SELECT SUM(DATEDIFF(DAY,[LEFT],[Return])) AS TOTALDAYS
FROM
(
select @left1 AS [Left],@return1 AS [Return]
UNION ALL
select @left2 AS [Left],@return2 AS [Return]
UNION ALL
select @left3 AS [Left],@return3 AS [Return]
) X
答案 3 :(得分:2)
您好,此查询可以为您提供帮助:
Select
sum(NbDay) as totaldiffday
From (
select datediff(day, @left1, @return1 ) As NbDay
Union
select datediff(day, @left2, @return2 ) As NbDay
Union
select datediff(day, @left3, @return3 ) As NbDay
) as SubQuery