sql server存储过程的问题

时间:2011-07-29 06:32:11

标签: sql-server-2005 stored-procedures

;with cte as
( 
  select FingerId, [Date],
         LogTime,
         row_number() over(partition by FingerId order by LogTime) as rn
  from InOut 
)
select C3.EmployeeName,C1.FingerId,
       C1.LogTime as InTime,
       C2.LogTime as OutTime,
       C2.[Date]
from cte as C1
  left outer join cte as C2
    on C1.FingerId = C2.FingerId and
       C1.rn + 1 = C2.rn INNER JOIN
           EmployeeMaster as C3 ON C3.Fingerid = C2.Fingerid
where C1.rn % 2 = 1 and  C3.EmployeeName = 'xyz' and C1.[Date] between '2011-07-21' and '2011-07-29' order by C2.[Date]

select * From Inout order by LogTime asc 

我有INOUT表它有5条记录和3条记录是2011-07-2011

InOuT表:

AutoId     FingerId      LogTime            Date
1            22          11:18:48 AM       2011-07-29
2            22          11:19:54 AM       2011-07-29
3            22          11:20:50 AM       2011-07-21
4            22          11:21:54 AM       2011-07-21
5            22          11:21:59 AM       2011-07-21

我通过以上查询获得此输出

EmployeeName  FingerId   InTime         OutTime        Date

xyz             22        11:20:50 AM    11:21:54 AM   2011-07-21 
xyz             22        11:18:48 AM    11:19:54 AM   2011-07-29

我想要这种类型的OutPut: -

EmployeeName  FingerId   InTime         OutTime        Date

xyz             22        11:20:50 AM    11:21:54 AM   2011-07-21
xyz             22        11:21:59 AM    ----          2011-07-21  
xyz             22        11:18:48 AM    11:19:54 AM   2011-07-29

这里第二行有InTime,我希望outtime应该显示“---”dash.But我没有得到这个查询。查询是正确的,但需要对此进行修改。

2 个答案:

答案 0 :(得分:1)

您必须在WHERE子句中使用C1。[Date]而不是C2。[Date] - 因为您在外部连接到C2并且您缺少的行具有C2的NULL值。[Date]。

答案 1 :(得分:1)

我对您现在发布的查询进行了一些修改,其中的更改以粗体突出显示:

;WITH cte AS
( 
  SELECT FingerId, [Date],
         LogTime,
         ROW_NUMBER() OVER(PARTITION BY FingerId ORDER BY LogTime) AS rn
  FROM InOut 
)
SELECT C3.EmployeeName,C1.FingerId,
       C1.LogTime AS InTime,
       C2.LogTime AS OutTime,
       COALESCE(C2.[Date], C1.[Date]) AS Date
FROM cte AS C1
  LEFT OUTER JOIN cte AS C2 ON C1.FingerId = C2.FingerId AND C1.rn + 1 = C2.rn
  INNER JOIN EmployeeMaster AS C3 ON C3.Fingerid = C1.Fingerid
WHERE C1.rn % 2 = 1
  AND C3.EmployeeName = 'xyz'
  AND C1.[Date] BETWEEN '2011-07-21' AND '2011-07-29'
ORDER BY C1.[Date]

最初我在考虑将SELECT子句中的C1.[Date]更改为C2.[Date],但是如果两个日期不同,我不确定它是否足够替代。你可以自己看看哪个选项更好,如果有的话。