【问题标题】:sql - selecting multiple dates from a table for unique ID'ssql - 从表中选择多个日期以获得唯一 ID
【发布时间】:2018-09-11 19:57:39
【问题描述】:

我有一张这样的数据表

所以我想让结果看起来像

唯一 ID、MIN(input_date)、MIN(date) where op='u'、max(date) where status=closed 以及关闭它的用户

这用于帮助台和跟踪何时输入帮助请求 (op=I)、何时分配帮助请求 (op='U' and status='open') 以及何时关闭 (op=u & status =关闭)。 I 的名字是需要帮助的用户,实际上并不关心他们,但跟踪提出请求的人很重要,因此最终想知道从输入到分配到完成需要多长时间。

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

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

如果什么都没发生,我需要它显示空值。所以对于 ident 3,它应该在分配的数据中读取 null 并且日期关闭,因为两者都没有发生。在 ident 2 中,它应该读取 null 表示关闭日期,因为它还没有关闭。

这是我此时得到的

【问题讨论】:

  • 如果您使用的是子查询,则根据外部表使用 where 条件

标签: sql sql-server


【解决方案1】:

您似乎需要条件聚合:

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;

【讨论】:

  • 谢谢。我以前从未使用过条件聚合,所以我学到了一些东西并花了 2 天时间来理解和使用它。我有一个小问题我无法解决。它没有输出正确的“技术”。如果我有 6 位可以分配和完成任务的技术人员,那么我想要一个 null 或他们的名字之一。问题是我的专栏包含他们的姓名和需要帮助的用户。我将 max(当 op='u' 然后 user end 的情况)写为'tech',我根据字母表得到最大的人,我只想要 6 个中的 1 个或 null。当我做 IN(list 6) 然后它给了我 6 字母表中的最后一个人。
  • @c0ry 。 . .我真的不关注评论。你能用样本数据和期望的结果问另一个问题吗?
  • 好的,发布新问题 - SQL - 从表中为唯一 ID 选择多个日期 - 第 2 部分
猜你喜欢
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多