在视图中通过 id 选择 MAX 值?

时间:2021-01-22 08:37:04

标签: sql sql-server tsql group-by min

我根据数据库中的几列创建了一个简单的视图

ALTER VIEW [BI].[v_RCVLI_Test] AS
Select distinct
    Borger.CPRnrKort as CPR,
    (...)
    IndsatsDetaljer.VisitationId as VisitationsId,
    Indsats.KatalogNavn as IndsatsNavn,
    (case
        when 
        (   
            Indsats.Model = 'SMDB2 Tilbudsmodel' or
            Indsats.Model = 'SMDB2 Samtalemodel' or
            Indsats.Model = 'Tilbudsmodel' or
            Indsats.Model = 'NAB Tilbudsmodel'
        )
        then IndsatsDetaljer.ServicePeriodeStart
        else IndsatsDetaljer.Ikrafttraedelsesdato
        end
    ) as StartDato,
    (case
        when 
        (   
            Indsats.Model = 'SMDB2 Tilbudsmodel' or
            Indsats.Model = 'SMDB2 Samtalemodel' or
            Indsats.Model = 'Tilbudsmodel'
        )
        then (case when IndsatsDetaljer.VisitationSlut = '9999-12-31' then convert(varchar(10), getdate(), 23) else IndsatsDetaljer.VisitationSlut end)
        when
        Indsats.Model = 'NAB Tilbudsmodel'
        then (case when IndsatsDetaljer.NABehandlingSlutDato = '9999-12-31' then convert(varchar(10), getdate(), 23) else IndsatsDetaljer.NABehandlingSlutDato end)
        else (case when IndsatsDetaljer.VisitationSlut = '9999-12-31' then convert(varchar(10), getdate(), 23) else IndsatsDetaljer.VisitationSlut end)
        end
    ) as StopDato,
    Refusion.Handlekommune as Handlekommune,
    replace(Refusion.Betalingskommune, 'Ukendt', 'Kendt') Betalingskommune

from nexus2.Fact_VisiteretTid as Fact

join nexus2.Dim_Paragraf Paragraf
on Fact.DW_SK_Paragraf = Paragraf.DW_SK_Paragraf
join nexus2.Dim_Indsats Indsats
on Fact.DW_SK_Indsats = Indsats.DW_SK_Indsats (...)

存在 StartDato 和 StopDato 的情况,因为这些日期来自不同的列。我已将日期“9999-12-31”转换为当前日期,因为我们稍后会进行一些时间计算,这样更方便。

CPR 是一个人的 id,VisitationsId 是这个人接受的服务的 id。 理论上,每个 VisitationsId 应该只有一个 StartDato 和一个 StopDato,但是由于文档系统中的一个小故障,我们有时会得到两个 StopDato:一个是正确的,一个是 '9999-12-31'(现在转换为当前日期)。

所以我需要按 VisitationsId 分组,然后只取 StopDato 的 MIN 值,但我有点不确定如何去做?

<头>
心肺复苏 访问 ID StartDato 停止数据 别的东西
123 56 2019-01-01 2019-12-12 东西
123 56 2019-01-01 9999-12-31 东西
123 58 2019-01-01 2019-12-14 东西
345 59 2018-11-01 9999-12-31 东西
345 55 2017-01-02 2017-11-12 东西
345 55 2017-01-02 9999-12-31 东西

在上表中,我需要删除第 2 行和第 6 行,因为 VisitationsId 与前一行相同,但它们在 StopDato 上有所不同。

在查询中的任何地方使用 group by 会给我另一个(看似随机的)列的错误,告诉我该列是:

<块引用>

在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

关于我如何去做这件事有什么建议吗?

1 个答案:

答案 0 :(得分:0)

添加一个过滤器来测试这个条件?

with cte (
    {your current query}
)
select *
from cte T
where not (
    StopDato = '9999-12-31'
    and exists (
       select 1
       from cte T1
       where T1.VisitationsId = T.VisitationsId
       and StopDato != '9999-12-31'
    )
);

而且您看起来好像正在将 StopDato 转换为一个很糟糕的 varchar - 在需要显示它们之前,您应该将日期视为日期。

相关问题