Domanda

I've got a hierarchy with the appropriate value linked to each level, let's say :


A               100
  A1            NULL
  A2            NULL
B
  B1            NULL
  B2            1000
      B21       500 
      B22       500
  B3            NULL

This hierarchy is materialized in my database as a parent-child hierarchy


Hierarchy Table
------------------------
Id       Code      Parent_Id
1          A          NULL
2          A1          1
3          A2          3
4          B          NULL
5          B1          4
6          B2          4
7          B21         6
8          B22         6
9          B3          4

And here is my fact table :


Fact Table
------------------------
Hierarchy_Id          Value
1                      100
6                      1000
7                      500
8                      500

My question is : do you know/have any idea of how to get only the last non empty value of my hiearchy? I know that there an MDX function which could do this job but I'd like to do this in an another way.

To be clear, the desired output would be :


Fact Table
------------------------
Hierarchy_Id          Value
1                      100
7                      500
8                      500

(If necessary, the work of flatten the hierarchy is already done...)

Thank you in advance!

È stato utile?

Soluzione

If the codes for your hierarchy are correct, then you can use the information in the codes to determine the depth of the hierarchy. I think you want to filter out any "code" where there is a longer code that starts with it.

In that case:

select f.*
from fact f join
     hierarchy h
     on f.hierarchyId = h.hierarchyId
where not exists (select 1
                  from fact f2 join
                       hierarchy h2
                       on f2.hierarchyId = h2.hierarchyId
                  where h2.code like concat(h.code, '%') and
                        h2.code <> h.code
                 )

Here I've used the function concat() to create the pattern. In some databases, you might use + or || instead.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top