适当的Orderby查询

时间:2013-05-16 15:04:12

标签: sql sql-server sql-order-by

鉴于以下内容:

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);

我无法按以下顺序显示结果。我想做的是让家长首先出现,然后是姓氏相同的人,最后是姓氏所有其他人

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

我试过这个

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

让我接近,但没有得到我想要的东西。

1 个答案:

答案 0 :(得分: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 with Demo