SQL Server how to group by ID and if Type is wo then get the value from case# and copy that value to wo Case# column for all the same Id in SSME

zwghvu4y  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(97)

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

IDTypeCase#wo Case#
101wo2323
101tsk1223
101tsk1323
101tsk1423
101tsk1523
642wo500500
642tsk34500
642tsk35500
642tsk36500
642tsk37500

I am not sure how to do this

Select * from TableA
a8jjtwal

a8jjtwal1#

You can use a window function and conditional aggregation:

SELECT *,
    MAX(CASE WHEN Type = 'wo' THEN [Case#] END) OVER(PARTITION BY ID) AS [wo Case#]
FROM TableA

Results:

IDTypeCase#wo Case#
101wo2323
101tsk1223
101tsk1323
101tsk1423
101tsk1523
642wo500500
642tsk34500
642tsk35500
642tsk36500
642tsk37500
777wo701702
777wo702702
777tsk703702
777tsk704702
999tsk91null
999tsk92null

The OVER(PARTITION BY ID) part allows the MAX() to extend its scope to all rows having the same ID value. The CASE...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 the OVER() clause.

See this db<>fiddle for a working example with a few extra test data rows.

相关问题