I am trying to write the SQL query to get the result.
Table A looks like below.
| ID | Type | Case# |
| ------------ | ------------ | ------------ |
| 101 | wo | 23 |
| 101 | tsk | 12 |
| 101 | tsk | 13 |
| 101 | tsk | 14 |
| 101 | tsk | 15 |
| 642 | wo | 500 |
| 642 | tsk | 34 |
| 642 | tsk | 35 |
| 642 | tsk | 36 |
| 642 | tsk | 37 |
Expecting the result
ID | Type | Case# | wo Case# |
---|---|---|---|
101 | wo | 23 | 23 |
101 | tsk | 12 | 23 |
101 | tsk | 13 | 23 |
101 | tsk | 14 | 23 |
101 | tsk | 15 | 23 |
642 | wo | 500 | 500 |
642 | tsk | 34 | 500 |
642 | tsk | 35 | 500 |
642 | tsk | 36 | 500 |
642 | tsk | 37 | 500 |
I am not sure how to do this
Select * from TableA
1条答案
按热度按时间a8jjtwal1#
You can use a window function and conditional aggregation:
Results:
The
OVER(PARTITION BY ID)
part allows theMAX()
to extend its scope to all rows having the same ID value. TheCASE...END
exclude all values except the one we are interested in.If there is a chance you might have more than one Type = 'wo' row for a given ID, you will need to consider which value should be used and perhaps modify the window function with an
ORDER BY
within theOVER()
clause.See this db<>fiddle for a working example with a few extra test data rows.