Skip to content
Advertisement

T-SQL sub select to retrieve rows with columns that have values instead of NULLs

This example is as close as I can demonstrate for the problem I’m trying to solve. For this case the sub-select has some mostly duplicated rows with the only difference being that some have a delvieryDate and some do NOT. If a row of data is available with the date, I want that. If not I’ll need to get the row without a date. I tried to fix the sub select with a “Top 1” & “Order by dDate desc” but T-SQL will not allow Order by in a sub-select.

For this example, I want row 9 instead of row 8 since the prior has a date. I also want row 10 since there is no equivalent available with a date.

enter image description here

Code:

Advertisement

Answer

For this data, one option would be to use aggregation, leveraging the fact that aggregate functions ignore null values:

Demo on DB Fiddle:

cName | Address       | Restaurant | fName              | mName         | dDate     
:---- | :------------ | :--------- | :----------------- | :------------ | :---------
Bill  | 123 1st St    | McDs       | Bacon & Egg Biscut | 1 - Breakfast | 11/01/2020
Bill  | 123 1st St    | McDs       | Happy Meal         | 2 - Lunch     | 11/01/2020
Bill  | 123 1st St    | Dominos    | Pizza              | 3 - Dinner    | 11/01/2020
Fred  | 111 Market St | McDs       | Bacon & Egg Biscut | 1 - Breakfast | 11/01/2020
Fred  | 111 Market St | McDs       | Happy Meal         | 2 - Lunch     | 11/01/2020
Fred  | 111 Market St | Dominos    | Pizza              | 3 - Dinner    | 11/01/2020
Lisa  | 01 Boulevard  | McDs       | Bacon & Egg Biscut | 1 - Breakfast | 11/01/2020
Lisa  | 01 Boulevard  | GrubHub    | Santa Fe Salad     | 2 - Lunch     | 11/01/2020
Lisa  | 01 Boulevard  | Dominos    | Pizza              | 3 - Dinner    | null      
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement