我有两个查询,我想将它们合并到SQL Server中的一个表中。
首先查询:
declare @NAME varchar(40), @startDate datetime, @endDate datetime
set @NAME='Nancy'
set @startDate='2014-04-2'
set @endDate='2014-04-28'
SELECT
USERINFO.USERID, USERINFO.NAME, USERINFO.TITLE, CHECKINOUT.CHECKTIME,
CHECKINOUT.CHECKTYPE, CHECKINOUT.trans
FROM
att..USERINFO
INNER JOIN
att..CHECKINOUT ON USERINFO.USERID = CHECKINOUT.USERID
WHERE
(USERINFO.NAME = @NAME)
AND (@NAME <> '-1')
AND (CHECKINOUT.CHECKTIME BETWEEN @startDate AND @endDate + ' 23:59:00.000')
OR (@NAME = '-1')
AND (CHECKINOUT.CHECKTIME BETWEEN @startDate AND @endDate + ' 23:59:00.000')
AND (1 = 1)
结果:
USERID NAME TITLE CHECKTIME CHECKTYPE trans
----------------------------------------------------------------------------
1003 Nancy Manufactura 2014-04-28 07:58:36.000 I 29
1003 Nancy Manufactura 2014-04-28 12:00:27.000 O 30
1003 Nancy Manufactura 2014-04-28 13:00:02.000 I 31
1003 Nancy Manufactura 2014-04-28 16:57:45.000 O 32
第二次查询:
SELECT
USERID
, convert(varchar(10),CHECKTIME,101) as Date
, SUM(CASE WHEN CHECKTYPE = 'I'
THEN -1 * (datepart(hh, [CHECKTIME]) + datepart(mi, [CHECKTIME]) / 60.0)
ELSE datepart(hh, [CHECKTIME]) + datepart(mi, [CHECKTIME]) / 60.0
END) AS Hours
, MAX(trans) as transs
INTO #temp
FROM att..[CHECKINOUT]
WHERE USERID = 1003
GROUP BY
USERID, CONVERT(varchar(10), [CHECKTIME], 101)
SELECT
USERID, Date, LEFT(Hours,2) as Hr, (RIGHT(Hours,6)*60) as Min, transs
INTO #temp2
FROM #temp
DROP TABLE #temp
SELECT
USERID, Convert(nvarchar(50), Hr) + Convert(nvarchar(50), Min) as HWORKED,
Date, transs
FROM #temp2
DROP TABLE #temp2
结果
USERID HWORKED Date transs
-----------------------------------------
1003 7.59000040 04/28/2014 32
1003 7.54000060 04/29/2014 36
1003 4957999960 04/30/2014 40
1003 4957999960 05/01/2014 44
我想要的结果是能够将两个查询放在一起并得到这个结果(使用trans作为连接:
USERID NAME TITLE CHECKTIME CHECKTYPE trans tranns HWORKED
-------------------------------------------------------------------------------------
1003 Nancy Manufactura 2014-04-28 07:58:36.000 I 29 NULL 0
1003 Nancy Manufactura 2014-04-28 12:00:27.000 O 30 NULL 0
1003 Nancy Manufactura 2014-04-28 13:00:02.000 I 31 NULL 0
1003 Nancy Manufactura 2014-04-28 16:57:45.000 O 32 32 7.59000040
答案 0 :(得分:1)
加入他们怎么样?表达它的最简单方法可能是使用ctes:
with t1 as (
<first query here>
),
t2 as (
<second query here>
)
select t1.*, t2.HWORKED, t2.Date
from t1 left outer join
t2
on t1.trans = t2.transs and t1.userid = t2.userid;