I have a large customer database where the customer table has people and their relationship to an organisation. People may belong to multiple organisations (this allows divisions within organisations). People with multiple organisations must have a default organisation, this is usually determined where isDefault = T, however the front end application can also figure the default application where isDefault = F by selecting the MIN(RowID).
So in the table below we know PersonId 3 has a default OrgID of 11 (IsDefault = T)
However, I need to figure out the query for finding PersonID 12's default.
ie
Select orgId as default from myTable
where personID = 12
and isDefault = 'T'
If 0 rows returned then perform a query like this:
Select orgId as default from myTable
where personID = 12
and
RowId in (select Min(rowId)
from myTable
where PersonId = 12)
RowID | PersonID | OrgId | isDefault
1 | 12 | 14 | F
2 | 12 | 17 | F
3 | 3 | 11 | T
4 | 3 | 14 | F
I think you can get what you want by ordering twice, first by whether IsDefault is T or F, then by RowId, and take the top result:
SELECT TOP 1 OrgId as [Default]
FROM MyTable
WHERE PersonId = 12
ORDER BY
CASE WHEN IsDefault = 'T' THEN 0 ELSE 1 END,
RowId
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With