Question

Here is my problem:

I have a unknown number of random events, each associated with a state number. Now I want a overall state number to describe the combination of random events' assignment. For example, if there is only 2 random events V1 and V2, each has 2 possible states, then below is my expected mapping, big V is my expected overall state number.

V v1 v2

1 1  1

2 2  1

3 1  2

4 1  2

my draft sql query is:

select t1.v1, t2.v2 from table1 as t1
  cross join table2 as t2

Now I want the big V generated from t1.v1 and t2.v2. I know the math algorithm but not SQL code. The math algorithm would be V = v1 + Max(v1)*(v2-1) for 2 random variables. My problem may need to address the case that there are more than 2 random variables.

Was it helpful?

Solution

For this, you can use either a subquery or a window function. I think the subquery might be clearer:

select v1 + maxv1*(v2 - 1) as V, t1.v1, t2.v2
from table1 t1 cross join
     table2 t2 cross join
     (select max(v1) as maxv1 from t1) maxt

By the way, you can assign a sequential number quite easily in SQL:

select row_number() over (order by v2, v1) as V, v1, v2
from table1 t1 cross join
     table2 t2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top