I have data in my database like this:
| Code | meta | meta_ID | date |
|---|---|---|---|
| A | 1,2 | 1 | 01/01/2022 08:08:08 |
| B | 1,2 | 2 | 01/01/2022 02:00:00 |
| B | null | 2 | 01/01/1900 02:00:00 |
| C | null | 3 | 01/01/2022 02:00:00 |
| D | 8 | 8 | 01/01/2022 02:00:00 |
| E | 5,6,7 | 5 | 01/01/2022 02:00:00 |
| F | 1,2 | 2 | 01/01/2022 02:00:00 |
I want to have this with the last date (comparing with day, month year)
| Code | meta | meta_ID | list_Code | date |
|---|---|---|---|---|
| A | 2,3 | 1 | A,B,F | 01/01/2022 08:08:08 |
| B | 1,3 | 2 | A,B,F | 01/01/2022 02:00:00 |
| C | null | 3 | C | 01/01/2022 02:00:00 |
| D | 8 | 8 | D | 01/01/2022 02:00:00 |
| E | 5,6,7 | 5 | E | 01/01/2022 02:00:00 |
| F | 1,2 | 3 | A,B,F | 01/01/2022 02:00:00 |
I want to have the list of code having the same meta group, do you know how to do it with SQL Server?
The code below inputs the 1st table and outputs the 2nd table exactly. The Meta and Date columns had duplicate values, so in the CTE I took the MAX for both fields. Different logic can be applied if needed.
It uses XML Path to merge all rows into one column to create the List_Code column. The Stuff function removes the leading comma (,) delimiter.