简体   繁体   English

将维度数据汇总到单行

[英]Summarise Dimension Data to single Row

I have a dimension with a number of attributes similar to the following which i have simplified for 1 Product and and a subset of the Columns:我有一个维度,其中包含许多类似于以下属性的维度,我已经为 1 个产品和列的一个子集进行了简化:

样本数据

What I want to be able to do is summarize: for a given ProdID, what is the current ClosedDate?我想要做的是总结:对于给定的 ProdID,当前的 ClosedDate 是什么? when did the Current closed date begin?当前关闭日期是什么时候开始的? What is the previous ClosedDate?以前的 ClosedDate 是什么? When did the previous ClosedDate begin?上一个 ClosedDate 是什么时候开始的?

eg from this example my answer would be:例如,从这个例子中我的答案是:

样本答案

The closed dates dont follow any particular ordering.关闭日期不遵循任何特定的顺序。 A product doesnt have to have a Closed Date, if so it is -1.产品不必有关闭日期,如果是,则为 -1。

I got as far as thinking i could use ROW_NUMBER() to index each history item as this would help with the most recent stuff, and the previous ClosedDate.我想我可以使用 ROW_NUMBER() 来索引每个历史项目,因为这将有助于处理最新的东西和以前的 ClosedDate。 I am stumped on how to get the previous Closed Date valid from, particularly in the case where I have 2 rows of history relating to 20200408.我不知道如何使上一个关闭日期有效,特别是在我有 2 行与 20200408 相关的历史记录的情况下。

Any suggestions appreciated.任何建议表示赞赏。

One option uses solely windows functions.一种选择仅使用 windows 功能。 Assuming that ties on closedDate are broken by picking the highest historyRow , that would be:假设通过选择最高的closedDate打破了historyRow的关系,那就是:

select 
    prodID,
    closedDate as closedDateCurrent,
    validFrom as closedDateCurrentStart,
    previousClosedDate,
    previousClosedDateStart
from (
    select
        t.*,
        row_number()    
            over(partition by prodID order by closedDate desc, historyRow desc) 
            as rn,
        lag(closedDate) 
            over(partition by prodID order by closedDate desc, historyRow desc) 
            as previousClosedDate,
        lag(validFrom) 
            over(partition by prodID order by closedDate desc, historyRow desc) 
            as previousClosedDateStart
    from mytable t
) t
where rn = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM