【问题标题】:count hours in same column在同一列中计算小时数
【发布时间】:2015-11-18 22:51:56
【问题描述】:

我正在尝试查询包含员工在场记录的表。它记录芯片的员工ID和日期时间如下:

id  datetime
3   2015-07-01 06:58:00.000
3   2015-07-01 12:01:00.000
3   2015-07-01 12:57:00.000
3   2015-07-01 19:17:00.000
3   2015-07-02 06:55:00.000
3   2015-07-02 14:05:00.000
15  2015-07-01 07:50:00.000
15  2015-07-01 12:01:00.000
15  2015-07-01 12:50:00.000
15  2015-07-01 18:04:00.000

我试图生成一个查询

id date       entrance   exit       2entrance   2exit
3  2015-07-01 06:58      12:01    12:57       19:17
3  2015-07-02 06:55      14:05    00:00       00:00
15 2015-07-01 07:50      12:01    12:50       18:04

但我正在寻找的最终结果是

id d1, d2, d3.. d31
3  11  7   12   6
15 9   0   6    12

(这是一整月每天的工作小时数)

为了得到这张表,我想用 excel 来处理以前的结果,但如果有人指出我正确的方向,我会很感激。

我们将不胜感激。

【问题讨论】:

  • 您正在尝试对数据进行透视,并对其进行动态透视。 SQL 结果集具有固定数量的列,因此要获得可变数量的列,您必须将查询构造为字符串。您最好在 Excel 中执行此操作。

标签: sql datetime sql-server-2005


【解决方案1】:

可能有点偏向另一个方向,但您可以将日期字符串拆分(因为它们具有固定格式 - yyyy-mm-dd_hh:mm:ss.mss)。 然后拿走你需要的东西。

我的第一个想法是编写一个小型 java 服务,它采用 .txt(您之前自动保存它),分割字符串,并为每个字符串以您需要的格式提供输出。

或者您正在寻找不涉及编程的东西?

【讨论】:

【解决方案2】:

试试:

create table #tmp (id int,log datetime) insert into #tmp select 3 , '2015-07-01 06:58:00.000' insert into #tmp select 3 , '2015-07-01 12:01:00.000' insert into #tmp select 3 , '2015-07-01 12:57:00.000' insert into #tmp select 3 , '2015-07-01 19:17:00.000' insert into #tmp select 3 , '2015-07-02 06:55:00.000' insert into #tmp select 3 , '2015-07-02 14:05:00.000' insert into #tmp select 15 , '2015-07-01 07:50:00.000' insert into #tmp select 15 , '2015-07-01 12:01:00.000' insert into #tmp select 15 , '2015-07-01 12:50:00.000' insert into #tmp select 15 , '2015-07-01 18:04:00.000' insert into #tmp select 3 , '2015-07-03 07:01:00.000' insert into #tmp select 3 , '2015-07-03 14:06:00.000' insert into #tmp select 3 , '2015-07-03 15:06:00.000' insert into #tmp select 3 , '2015-07-03 18:06:00.000' select id, [1] as Day1 ,[2] as Day2, [3] as Day3 from ( select Result.id, Result.Day, sum(Result.Diff*Result.Signal)/60 as Hours from ( select Result1.id, Result1.Day, DATEDIFF(minute, Result1.Time, Result2.Time) as Diff, ROW_NUMBER() over( order by Result1.id) % 2 as Signal from ( select id, datepart(day, log) as Day, log as Time, ROW_NUMBER() over( order by id) as RowID from #tmp ) as Result1 left join ( select id, datepart(day, log) as Day, log as Time, ROW_NUMBER() over( order by id) as RowID from #tmp ) as Result2
on Result1.RowID = Result2.RowID -1 and Result1.Day = Result2.Day ) as Result group by Result.id, Result.Day ) as PivotSource pivot ( sum(Hours) for Day in ( [1] ,[2], [3] ) ) as PivotTable

您可以根据需要延长 PIVOT 天数,并且可以使用您的表插入 #tmp。 问候,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-02
    • 2020-10-10
    • 2018-03-07
    • 2018-12-24
    • 2019-11-02
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多