【问题标题】:Calculate data in Pivot在 Pivot 中计算数据
【发布时间】:2021-03-25 13:01:17
【问题描述】:

我有以下 4 列的 SQL 表。

表名:tblTimeTransaction

列:EmployeeNumber、TransactionDate、CodeType、TimeShowninSeconds

CodeType 的值分别为 REG、OT1、OT2、OT3

我希望它从 2020 年 1 月 1 日起使用 15 天增量使用数据透视表显示:

Employee Number | Effective Date        | REG   | OT1 | OT2     | OT3
E12345      | Between 10-1 till 10-15   | 200   | 100 | 50      | 45 
E15000      | Between 10-1 till 10-15   | 400   | 600 | 903     | 49
E12345      | Between 10-15 till 10-31  | 200   | 100 | 50      | 45 
E15000      | Between 10-15 till 10-31  | 400   | 600 | 903     | 49
E12346      | Between 11-1 till 11-15   | 4200  | 100 | 50      | 45 
E15660      | Between 11-1 till 11-15   | 1200  | 600 | 6903    | 49

到目前为止我的 SQL 代码:

SELECT 
    Employee Number, 
    [TransactionDate] as [Effective Date], 
    [REG], 
    [OT1],
    [OT2],
    [OT3] 
    
FROM 
       ( SELECT Employee Number, TransactionDate, CodeType, TimeInSeconds
         FROM [tblTimetransaction] 
       ) ps
PIVOT
       ( SUM (TimeInSeconds)
         FOR CodeType IN ( [REG], [OT1], [OT2], [OT3])
       ) AS pvt
where TransactionDate between '2020-01-01' and '2020-12-31'
    

【问题讨论】:

    标签: sql sql-server datetime pivot date-arithmetic


    【解决方案1】:

    如果我没听错,您可以将 effective_date 截断为每月 15 日的 1 日,具体取决于当月的某天,然后使用条件聚合来计算 @987654322 的总数@为每个code_type:

    select employee_number,
        datefromparts(year(effective_date), month(effective_date), case when day(effective_date) < 15 then 1 else 15 end) as dt,
        sum(case when code_type = 'REG' then time_in_seconds else 0 end) as reg,
        sum(case when code_type = 'OT1' then time_in_seconds else 0 end) as ot1,
        sum(case when code_type = 'OT2' then time_in_seconds else 0 end) as ot2,
        sum(case when code_type = 'OT3' then time_in_seconds else 0 end) as ot3
    from tblTimetransaction
    where effective_date >= '20200101' and effective_date < '20210101'
    group by employee_number, 
        datefromparts(year(effective_date), month(effective_date), case when day(effective_date) < 15 then 1 else 15 end)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-23
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      相关资源
      最近更新 更多