I have a dataset where I'm trying to sort by having null startdate values first, then by lastname. Then nonnull startdates, also by last name:
declare @t table
(lastname varchar(100),
firstname varchar(50),
startdate date)
insert into @t
values('Smith', 'John', '01/01/2023'),
('Marshall', 'Tom', NULL),
('Thomas', 'Frank', '01/01/2022'),
('Schmidt', 'Mike', NULL),
('Carter', 'Gary', '03/01/2023'),
('Belle', 'Albert', NULL)
LastName FirstName StartDate
Smith John 2023-01-01
Marshall Tom NULL
Thomas Frank 2022-01-01
Schmidt Mike NULL
Carter Gary 2023-03-01
Belle Albert NULL
Desired Output:
LastName FirstName StartDate
Belle Albert NULL
Marshall Tom NULL
Schmidt Mike NULL
Carter Gary 2023-03-01
Smith John 2023-01-01
Thomas Frank 2022-01-01
I've tried doing a Union:
select *
into #nulls
from @t
where startdate is null
order by lastname
select *
into #nonnulls
from @t
where startdate is not null
order by lastname
select *
from #nulls
UNION
select *
from #nonnulls
I've also tried using Order by Case:
select *
from @t
order by case when startdate is null then lastname
when startdate is not null then lastname end
1条答案
按热度按时间7fhtutme1#
A more efficient version of the
ORDER BY CASE
is to useUNION ALL
to combine the two halves, and sort it using an ordering columnThis allows the server to use a Merge Concatenation rather than a Sort.