使用内部查询中的值更新表列?

时间:2018-06-29 16:28:00

标签: sql-server sql-update inner-query

我有下表:

create table public.dctable
(
     prod int, 
     customer varchar(100), 
     city varchar(100), 
     num int, 
     tim datetime, 
     dc smallint
);

insert into dctable 
values (1, 'Jim', 'Venice', 5, '2015-08-27 1:10:00', 0),
       (1, 'Jim', 'Venice', 5, '2015-08-27 1:10:15', 0),
       (1, 'Jim', 'Venice', 5, '2015-08-27 1:10:28', 0),
       (4, 'Jane', 'Vienna', 8, '2018-06-04 2:20:43', 0),
       (4, 'Jane', 'Vienna', 8, '2018-06-04 2:20:45', 0),
       (4, 'Jane', 'Vienna', 8, '2018-06-04 2:20:49', 0),
       (4, 'Jane', 'Vienna', 8, '2018-06-04 2:30:55', 0),
       (7, 'Jack', 'Vilnius', 4, '2015-09-15 2:20:55', 0),
       (7, 'Jake', 'Vigo', 9, '2018-01-01 10:20:05', 0),
       (7, 'Jake', 'Vigo', 2, '2018-01-01 10:20:25', 0);

现在,我想在此查询中将列dc更新为tdc的值:

select 
    t.*,
    (case 
        when lead(tim) over (partition by prod, customer, city, num order by tim) <= dateadd(second, 30, tim)
           then 1
           else 0
     end) as tdc
from 
    public.dctable t

所以我尝试了这个:

update public.dctable
set dc = b.tdc
from 
    (select 
         t.*,
         (case 
             when lead(tim) over (partition by prod, customer, city, num order by tim) <= dateadd(second, 30, tim)
                then 1
                else 0
          end) as tdc
     from    
         public.dctable t) b
where 
    public.dctable.prod = b.prod
    and public.dctable.customer = b.customer
    and public.dctable.city = b.city
    and public.dctable.num = b.num;

但是当我查询结果时,所有行的dc仍为0。

select * from public.dctable;

prod        customer    city    num tim                   dc
-------------------------------------------------------------
1           Jim         Venice  5   2015-08-27 01:10:00   0
1           Jim         Venice  5   2015-08-27 01:10:28   0
1           Jim         Venice  5   2015-08-27 01:10:15   0
4           Jane        Vienna  8   2018-06-04 02:20:49   0
4           Jane        Vienna  8   2018-06-04 02:20:45   0
4           Jane        Vienna  8   2018-06-04 02:30:55   0
4           Jane        Vienna  8   2018-06-04 02:20:43   0
7           Jake        Vigo    2   2018-01-01 10:20:25   0
7           Jack        Vilnius 4   2015-09-15 02:20:55   0
7           Jake        Vigo    9   2018-01-01 10:20:05   0

如何从上面的内部查询中将列dc更新为tdc的值?

谢谢

1 个答案:

答案 0 :(得分:0)

这似乎是您想要的。

SQL Fiddle

update d
  set d.dc = b.dc2
from dctable d
inner join 
      (select 
         *, 
         dc2 = case 
           when lead(tim) over (partition by prod, customer, city, num order by tim) <= dateadd(second, 30, tim)
           then 1
           else 0
         end
       from dctable) b on
            d.prod = b.prod
        and d.customer = b.customer
        and d.city = b.city
        --and d.tim = b.tim    --you may also want this join clause.
        and d.num = b.num;



select * from dctable