应该为不存在的元素生成内容的SQL查询

应该为不存在的元素生成内容的SQL查询,sql,postgresql,join,union,Sql,Postgresql,Join,Union,这张桌子看起来像这样 doc_id is the customer device st1 and st2 are some states of this device datetime is the date of a transition between them 我需要做的是生成一个输出表,告诉我每个doc\u id 问题是并不是每个doc\u id都有每个状态。 结果应该如下所示: 我不知道该怎么做。 因此,首先,我所做的是union all“为doc\u id对每个状态进行合并,这

这张桌子看起来像这样

doc_id is the customer device
st1 and st2 are some states of this device
datetime is the date of a transition between them

我需要做的是生成一个输出表,告诉我每个
doc\u id

问题是并不是每个
doc\u id
都有每个状态。 结果应该如下所示:

我不知道该怎么做。 因此,首先,我所做的是
union all
“为
doc\u id
对每个状态进行合并,这样我就可以找到
2
状态的第一次出现,以及
6
状态的最后一次出现。 问题是,对于聚合函数,如果说这种广义的
state\u id
从未发生在
doc\u id
我可以得到如下结果:

1 01.01.2014
2 05.01.2014

在单独的表中,但我不知道如何组合这些输出以获得应有的结果。
有什么想法吗?

一种方法是条件聚合:

select doc_id,
       min(datetime) filter (where st1 = 2) as s2_firststate2,
       max(datetime) filter (where st2 = 6) as s2_laststate6
from t
group by doc_id;
你的列名令人困惑;他们建议您只关心
st2
。然而,结果表明,你关心这两个问题。这些都是过渡,因此上面的内容应该有效,但您可能还需要:

       min(datetime) filter (where 2 in (st1, st2)) as s2_firststate2,
       max(datetime) filter (where 6 in (st1, st2)) as s2_laststate6

@Simullacra
filter
是SQL标准语法,但Postgres是少数支持它的数据库之一。
       min(datetime) filter (where 2 in (st1, st2)) as s2_firststate2,
       max(datetime) filter (where 6 in (st1, st2)) as s2_laststate6