sql - 从表中选择多个日期以获取唯一ID

时间:2018-04-02 15:26:31

标签: sql sql-server

我有一个数据表就是这样

enter image description here

所以我想让结果看起来像

唯一ID,MIN(input_date),MIN(日期),其中op =' u',max(日期),其中status =已关闭,用户已将其关闭

这是用于帮助台和跟踪输入帮助请求时(op = I),分配时(op =' U' U'和='打开')和当它关闭时(op = u& status = closed)。我的名字是需要帮助的用户,并且真的不关心他们,但跟踪执行请求的人很重要,因此最终想知道从输入到分配到完成需要多长时间。

我的查询是使用子查询,但它将每列中的日期输出为同一日期,并将所有行的同一个人输出。

select ident,
(select ident, MIN(input_date)
from table
where op='I' and input_date >'2017-12-31') as 'input date'
(select MIN(date)
from table
where op='U' and input_date > '2017-12-31') as 'date assigned',
(select MAX(date)
from table
where op='U' and status='closed' and input_date > '2017-12-31')    as 'date closed',
(select max(user)
from table
where op='u' and status='closed' and input_date >'2017-12-31') as 'tech'
from table
where input_date >'2017-12-31'
group by ident
order by ident asc

如果没有发生,我需要它显示null。所以对于ident 3,它应该在分配的数据和关闭日期时读取null,因为两者都没有发生。在ident 2中,它应该在关闭日期时读取null,因为它尚未关闭。

这是我此时得到的

enter image description here

1 个答案:

答案 0 :(得分:0)

您似乎想要条件聚合:

select id,
       min(input_date),
       min(case when op = 'u' then date end),
       max_close_date,
       max(case when status = 'closed' and date = max_close_date then user end)
from (select t.*,
             max(case when status = 'closed' then date end) over (partition by id) as max_close_date
      from t
      where input_date > '2017-12-31'
     ) t
group by id, max_close_date;
相关问题