【发布时间】:2021-04-26 17:17:25
【问题描述】:
我已经根据我们数据库中的几列创建了一个简单的视图
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 值,但我有点不确定如何去做?
| CPR | VisitationsId | StartDato | StopDato | Something Else |
|---|---|---|---|---|
| 123 | 56 | 2019-01-01 | 2019-12-12 | Something |
| 123 | 56 | 2019-01-01 | 9999-12-31 | Something |
| 123 | 58 | 2019-01-01 | 2019-12-14 | Something |
| 345 | 59 | 2018-11-01 | 9999-12-31 | Something |
| 345 | 55 | 2017-01-02 | 2017-11-12 | Something |
| 345 | 55 | 2017-01-02 | 9999-12-31 | Something |
在上表中,我需要删除第 2 行和第 6 行,因为 VisitationsId 与上一行相同,但它们在 StopDato 上存在差异。
在查询中的任何位置使用 group by 都会在另一个(看似随机的)列上给我一个错误,告诉我该列是:
在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
对我如何做这件事有什么建议吗?
【问题讨论】:
-
请用一些示例数据创建一个minimal reproducible example 来说明您的意思。只需过滤掉日期为
'9999-12-31'的所有行? -
@DaleK 否,'9999-12-31' 仅在 VisitationsId 不唯一的行上才无效。我根本不应该有任何重复的 VisitationsId,而且是额外的 StopDato 造成了问题。除此之外,我已经尽了我最大的努力,一个最小的可重现示例 - 使用所有连接,显示示例数据几乎是不可能的......
-
@DaleK 添加了一个简单的表格来更好地说明 - 希望它有意义!
标签: sql sql-server tsql group-by min