按索引获取同一个表中的值

时间:2017-11-08 11:34:15

标签: sql sql-server

我有像这张照片的结构

enter image description here

如何获得datte列的值ke列的值

我想在DATEDIFF

使用功能DATTE

1 个答案:

答案 0 :(得分:0)

declare @t table (KE int, name varchar(100), datte date);
insert into @t values 
(1, 'CAT1', '20170101'), (2, 'CAT1', '20170102'), 
(1, 'CAT2', '20170201'), (2, 'CAT2', '20170215'), 
(1, 'CAT3', '20170112');

with cte as
(
select 
       name,
       max(case ke when 1 then datte end) as start_dt,
       max(case ke when 2 then datte end) as finish_dt
from @t 
group by name
)

select *, datediff(day, start_dt, finish_dt) as days
from cte;