sql-server - 如何在sql server中使用像pivote结果

标签 sql-server stored-procedures

 Insert into @temp3
 select 
 Distinct t.staffName,
    attendDate = convert(date,t.AttendDate)

  , t.staffId
  , t.Firmid
  ,t.ShiftName
  , t.attendId
  , CheckIn  = convert(time(0),t.AttendDate)
  , CheckOut = convert(time(0),x.AttendDate)
from @temp2 as t
outer  apply (
  select top 1 i.AttendDate
  from @temp2  as i
  where t.staffid = i.staffid
    and i.attendDate > t.attendDate
  order by i.attendDate desc
) x
where t.InOutMode = 'CheckIn'

How to get First CheckIn and Last Check Out Value?

[I want to display checkIn and CheckOut as a column 请检查第一张图片我想获得第一次 checkin 和最后一次 checkout

我有以下结果,我想将 checkin 和 checkout 显示为列 喜欢

-------------------------------------------------------------------------------
atteDate  | staffName      |  staffId | Firmid |attendId | CheckIn |CheckOut |
--------------------------------------------------------------------------------
2014-11-13|Urvashi A Patel |7023     |6012 | 204 | 9:30:03 | 18:34:17

最佳答案

使用聚合查询,按 attendDate 的日期分组。

select 
    attendDate = convert(date,t.AttendDate)
  , t.staffName
  , t.staffId
  , t.Firmid
  , attendId   = min(t.attendId)
  , CheckIn    = min(convert(time(0),t.AttendDate))
  , CheckOut   = max(convert(time(0),t.AttendDate))
from t
group by 
    t.staffName
  , t.staffId
  , t.Firmid
  , convert(date,t.attendDate)

如果您收到错误是因为您尝试将其与某些可为您提供上述结果的查询一起使用,则最好在您的问题中包含该查询。

如果是这种情况,则使用 common table expression可能有帮助。

;with cte as (
/* query that does stuff to get the results in your question */
)

select 
    attendDate = convert(date,t.AttendDate)
  , t.staffName
  , t.staffId
  , t.Firmid
  , attendId   = min(t.attendId)
  , CheckIn    = min(convert(time(0),t.AttendDate))
  , CheckOut   = max(convert(time(0),t.AttendDate))
from t
group by 
    t.staffName
  , t.staffId
  , t.Firmid
  , convert(date,t.attendDate)

关于sql-server - 如何在sql server中使用像pivote结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43046216/

相关文章:

python - 我可以将 pyodbc executemany 与 sql 存储过程一起使用吗?

mysql存储过程,使用列名作为参数

mysql - 检查 MySQL 函数中是否存在一行

SQL Server 脚本 2012 项目到 Team Foundation Server 2012

java - MS-SQL Server、JDBC 和 XA 事务异常

sql-server - SQL Server MERGE 语句和 ORDER BY 子句

sql - 如何向 SQL Server 中已存在的列添加非空值?

c# - 我可以使用C#锁来防止Web应用程序中的SQL Server死锁吗?

mysql 过程 - 子句中的 where 条件中的解析参数问题

mysql - 在 MySQL 给定条件下生成所有可能的唯一和随机值