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
我在sql中执行此查询,我收到了错误:
消息207,级别16,状态1,行10无效的列名称“w”。消息207, 级别16,状态1,行11无效的列名称“W”。
答案 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;