【问题标题】:How to create a calculated field with a where clause in the calculation如何在计算中创建带有 where 子句的计算字段
【发布时间】:2019-06-11 19:10:17
【问题描述】:

The image shows the table from this code: select * from PunchClock where punchmonth = 1 and PunchDay = 1 and PunchYear = 2018

我正在尝试计算数据库中每天工作的小时数。我们的表有 2 列与此相关。 InOut 是具有 1 或 0 的列(1 = 打卡,0 = 打卡),然后是打卡日期时间。我如何使用这两个字段来计算每天工作的小时数。

我试图从打卡超时中减去打卡时间,但这不起作用。

select PunchMonth, PunchDay, PunchYear, 
      ((PunchDateTime where InOut = 0) - (punchdatetime where InOut = 1))
  from PunchClock

错误消息:关键字“where”附近的语法不正确。

【问题讨论】:

  • 看起来你有一个表,其中有一条打卡记录和一条打卡记录。这将需要的不仅仅是来自单个表的简单查询。样本数据和结果肯定会有所帮助。

标签: sql sql-server


【解决方案1】:

可能是你需要案例(不是在哪里)

select PunchMonth
  , PunchDay
  , PunchYear
  , case INOut = 0 then PunchDateTime else -PunchDateTime end
from PunchClock

【讨论】:

    【解决方案2】:

    我想你想要一个case 表达式。此外,由于给定行的 InOut 值为 01 但不是两者兼有,我认为您需要聚合。

    所以,我猜:

    select PunchMonth, PunchDay, PunchYear,
           datediff(second, min(case when InOut = 0 then punchdatetime end),
                    max(case when InOut = 1 then punchdatetime  end)
                   ) as seconds_diff
    from PunchClock
    group by PunchMonth, PunchDay, PunchYear;
    

    【讨论】:

      猜你喜欢
      • 2011-10-25
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      相关资源
      最近更新 更多