问题
My table looks like this:
|--------|--------|--------|--------|---------|---------|
| num_1 | num_2 | num_3 |level_1 | level_2 | level_3 |
|--------|--------|--------|--------|---------|---------|
| 1111 | 3333 | 4444 | false | false | false |
|--------|--------|--------|--------|---------|---------|
| 1111 | 3333 | 5555 | false | false | false |
|--------|--------|--------|--------|---------|---------|
| 1111 | 6666 | null | false | false | false |
|--------|--------|--------|--------|---------|---------|
| 1111 | 7777 | 8888 | false | true | false |
|--------|--------|--------|--------|---------|---------|
So that the table looks like this:
|--------|--------|--------|--------|---------|---------|-------------|
| num_1 | num_2 | num_3 |level_1 | level_2 | level_3 | result |
|--------|--------|--------|--------|---------|---------|-------------|
| 1111 | 3333 | 4444 | false | false | false | 3333 |
|--------|--------|--------|--------|---------|---------|-------------|
| 1111 | 3333 | 5555 | false | false | false | 3333 |
|--------|--------|--------|--------|---------|---------|-------------|
| 1111 | 6666 | null | false | false | false | 6666 |
|--------|--------|--------|--------|---------|---------|-------------|
| 1111 | 7777 | 8888 | false | true | false | 8888 |
|--------|--------|--------|--------|---------|---------|-------------|
Edit
This is a simplified example, but here is how this table works:
- The
num_xcolumns reference the ID to an element in another table, which might or might not have a certain attribute we're looking for. - The
level_xcolumns represents whether the columnnum_xwith the samexvalue has that certain attribute set totrue. These entries represent a hierarchy of elements which do or do not have that attribute:
1111 ✘ > 3333 ✘ > 4444 ✘
> 5555 ✘
> 6666 ✘
> 7777 ✓ > 8888 ✘
My goal is to go through the whole table, and find the lowest level for each row at which the previous level has no child level with a true value.
For example, for the first few rows, since all rows are children of 1111 and that 1111 has a child, 7777, with its attribute set to true, all other children at the same level as 7777 would be the result of their own row, unless they do have children with their attribute set to true as well.
Since 7777 has its attribute set to true, the result of this row is its immediate child, 8888. If it did not have a child, the row would not need a result.
回答1:
The following simple logic returns the values you specify. It is not clear if this is what you actually intend:
select (case when not level_2 then num_3
else num_2
end)
My best guess is that a relatively simple case expression is what you need. I am just unclear on what you really need.
来源:https://stackoverflow.com/questions/64692467/case-when-over-partition-by-applied-per-row