2

Given the following:

Create Table Person
(
     ID         int ,
     Lastname   varchar(32),
     Firstname  varchar(32)
);

Create Table Families
(
     ID int,
     PersonId_fk int,
     IsHeadOfHousehold bit
);

Insert into Person Values(1, 'Smith', 'John');
Insert into Person Values(4, 'Johnson', 'Sue');
Insert into Person Values(2, 'Smith', 'Jane');
Insert into Person Values(3, 'Towmater', 'Billy');

Insert into Families Values(1, 1, 1);
Insert into Families Values(1, 2, 0);
Insert into Families Values(1, 3, 0);
Insert into Families Values(1, 4, 0);

I am having trouble getting the results to appear in the following order. What I am trying to do, is get the head of the household to appear first, followed by anyone with the same last name, and finally everyone else ordered by last name

Smith     John      1
Smith     Jane      0
Johnson   Sue       0
Towmater  Billy     0

I've tried this

SELECT LastName, FirstName, IsHeadOfHousehold
FROM families f
join person p
on f.PersonID_fk = p.ID
where f.Id = 1
Order by IsHeadOfHousehold DESC, LastName, FirstName

which gets me close, but doesn't get me what i want.

4

1 回答 1

2

由于您使用的是 SQL Server,如果您使用的是 2005+,您应该能够使用row_number()来对数据进行排序:

SELECT LastName, FirstName, IsHeadOfHousehold
FROM families f
join person p
  on f.PersonID_fk = p.ID
where f.Id = 1
order by IsHeadOfHousehold desc, 
  row_number() over(partition by lastname order by IsHeadOfHousehold desc) desc, 
  lastname, firstname;

请参阅带有演示的 SQL Fiddle

于 2013-05-16T15:10:43.803 回答