需要更新表attrans

时间:2016-02-17 12:50:52

标签: sql sql-server database

我有一张表attrans

[Card_ID],
[date_att],
[time_att],
[Transaction_type],
[Processed],
[Shift_No],
[Shift_Type],
[Instead],
[user_id],
[tran_id]

transaction_type表示(1 in 2 out)

此表中的员工交易,员工可以获得in 21-1-2016 20:30 out 23-01-2016 8:30

我需要更新此表格,以便让所有用户20:30获得in 8:30 and 8:30 if get in 20:30

并根据时间进入8:3020:30进行交易

2 个答案:

答案 0 :(得分:0)

通过联接技术可能的解决方案:

;with Attrans as
(
  select cast(1 as int) as [user_id], cast(1 as int) as transaction_type,
    cast('2015-12-31' as date) as date_att, cast('8:30' as time) as time_att
  union all
  select 1, 2, '2015-12-31', '16:00'
  union all
  select 1, 1, '2016-01-01', '20:30'
  union all
  select 1, 2, '2016-01-02', '10:30'
)
select
  a_in.*,
  a_out.date_att as date_out,
  cast(case when a_out.date_att = a_in.date_att then '20:30' else '8:30' end as time) as time_out
from Attrans a_in
inner join Attrans a_out on a_out.user_id = a_in.user_id 
  and (a_out.date_att = a_in.date_att and a_in.time_att = '8:30'
    or a_out.date_att = dateadd(dd, 1, a_in.date_att) and a_in.time_att = '20:30')
where a_in.transaction_type = 1 and a_out.transaction_type = 2
order by a_in.date_att

当然,如果真正的任务更复杂(例如,为用户折叠每天生成的多行),您将需要一些其他方法。

答案 1 :(得分:0)

理解你想要什么是有点挑战,因为没有StartTime和EndTime(我对时间计时系统有一些经验)。我可以建议你UPDATE wit CASE方法。如果您提供更多信息,我可以帮助您根据情况进行调整。 [time_att]是时间记录吗?它似乎是[时间参加]字段

UPDATE
        [attrans]
    SET
        [EndTime] =
        (
            CASE [EndTime]
                WHEN '08:30' THEN '20:30' 
                WHEN '20:30' THEN '08:30'
            ELSE
                -- do nothing
            END
        )

        ,[StartTime] = 
        (
            CASE [EndTime]
                WHEN '20:30' THEN '08:30'
                WHEN '08:30' THEN '20:30'
            ELSE
              -- do nothing
            END
        )