计算太阳日期时间时出错

时间:2013-09-05 08:57:48

标签: sql

SELECT *, 
  ROW_NUMBER() OVER (ORDER BY checktime)RN 
INTO   XYZZ
FROM   test 
where  checktime>='2013-08-14 00:00:00.000' 
  and  checktime<='2013-08-14     23:00:00.000'     

........ 1

SELECT t1.*, 
  ( t2.checktime - t1.checktime) as w
FROM   XYZZ t1 
LEFT JOIN XYZZ t2 ON t1.RN = t2.RN - 1
union all
select null,null,null,null,null,null,null,null,null,
  Convert(varchar(10),sum(DatePart(hh,w)))+':'+
  Convert(varchar(10),sum(DatePart(mi,W)))
From XYZZ

... 2

  1. 工作正常,但2不能正常工作
  2. 我在sql中执行此查询,我收到了错误:

      

    消息207,级别16,状态1,行10无效的列名称“w”。消息207,   级别16,状态1,行11无效的列名称“W”。

1 个答案:

答案 0 :(得分:0)

你不能那样做,你不能在单独处理UNION ALL之后在第二个查询中引用别名,但你可以这样做:

SELECT t1.*, (t2.checktime - t1.checktime) as w
FROM   XYZZ t1 
LEFT JOIN XYZZ t2 ON t1.RN = t2.RN - 1
UNION ALL
SELECT null,null,null,null,null,null,null,null,null,
  Convert(varchar(10),sum(DatePart(hh,w)))+':'+
  Convert(varchar(10),sum(DatePart(mi,W)))
From
(
    SELECT t1.*, (t2.checktime - t1.checktime) as w
    FROM   XYZZ t1 
    LEFT JOIN XYZZ t2 ON t1.RN = t2.RN - 1
) AS t;

OR

WITH CTE
AS
(
    SELECT t1.*, (t2.checktime - t1.checktime) as w
    FROM   XYZZ t1 
    LEFT JOIN XYZZ t2 ON t1.RN = t2.RN - 1
)
SELECT *
FROM CTE
UNION ALL
SELECT null,null,null,null,null,null,null,null,null,
  Convert(varchar(10),sum(DatePart(hh,w)))+':'+
  Convert(varchar(10),sum(DatePart(mi,W)))
FROM CTE;