0

我有一张桌子:

Date, HoursToWork, Workers_ID, Contract_ID, ContractStartDate

我的目标是汇总当前合同的所有时间,因为从 01.01 开始,合同每年每天都会发生变化。- 31.12.. 可能有“n”个合同。我们可以使用 Contract_ID(如果有多个 ID,则最高 ID 始终是当前合约)或 ContractStartDate。我创建的表(见上文)具有以下结构:如果一个工人有两个合同,他每个日期都有两个条目。一份用于合同 1,一份用于合同 2。例如

01-01-2013, 8, 1, 1, 01.01.2013
01-01-2013, 4, 1, 2, 03.05.2013

假设工人每天工作 8 小时(不考虑假期等),我们将每个工作日加起来 8 小时,直到 2013 年 5 月 2 日。现在合同发生了变化,他每天工作 4 小时,我们开始在已经收集的每个工作日增加 4 小时,直到年底。

4

3 回答 3

0

Your clarification is that you want this by user. To get the current contract, use row_number() and choose the most recent ContractId for each user. Then, just do the aggregation:

select workers_id, ContractId, ContractStartDate, SUM(HoursToWork)
from (select t.*,
             ROW_NUMBER() over (partition by Workers_Id order by Contract_id desc) as seqnum
      from t
     ) t
where seqnum = 1
group by workers_id, ContractId, ContractStartDate;

To use this in your process, you will want something like where Workers_ID = @Workers_Id to select the current worker.

The row_number() function assigns a sequential number to each row for each worker (because of the partition by clause. The first row is the one with the highest contract id (because of theorder by` clause).

于 2013-06-04T15:19:13.277 回答
0

尝试:

select sum(h.HoursToWork)
from (select max(contract_ID) contract_ID
      from contracts_table
      where XXX=workers_ID) c
join hours_table h on c.contract_ID = h.contract_ID
于 2013-06-04T15:14:58.230 回答
0

I suppose this should work:

select Workers_ID, sum(CASE WHEN dt1 is null THEN dt2 ELSE dt1 END) from
(select Workers_ID,

   DATEDIFF(DAY,
            ContractStartDate,
            (select top 1 ContractStartDate from yourTable t2
                where t2.Workers_ID=t1.Workers_ID 
                and t2.ContractStartDate>t1.ContractStartDate)
           )  * HoursToWork as dt1,
   DATEDIFF(DAY,
            ContractStartDate,
            GetDate()
           )  * HoursToWork as dt2               
from yourTable t1) a
group by Workers_ID

See fiddler

于 2013-06-04T15:35:39.577 回答