基于整数键对SQL中的行进行排序

时间:2014-09-03 00:07:11

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

我有一个非常简单的表,如下所示:

---------------------------------------------------------
| CategoryId | CategoryName             | SubCategoryId |
|------------|--------------------------|---------------|
| 32         | Sports Bar               | 30            |
| 29         | Automotive Services      | 0             |
| 120        | Dance Studio             | 116           |
| 116        | Arts and Hobbies         | 0             |
| 24         | Telecommunications       | 0             |
| 40         | Body Shop                | 29            |
| 41         | Tires                    | 29            |
| 30         | Restaurant/Tavern        | 0             |
| 60         | Coffee House             | 30            |
---------------------------------------------------------

SubCategoryId确定该类别应属于哪个类别。如果是0,那么这意味着它是顶级类别。例如,Tires属于类别ID为29的类别,即Automotive Services

我的问题是,如何对此进行排序,以便首先列出顶级类别,然后是该类别下的子类别。例如,在上表中,我希望它按如下方式排序:

---------------------------------------------------------
| CategoryId | CategoryName             | SubCategoryId |
|------------|--------------------------|---------------|
| 116        | Arts and Hobbies         | 0             |
| 120        | Dance Studio             | 116           |
| 29         | Automotive Services      | 0             |
| 40         | Body Shop                | 29            |
| 41         | Tires                    | 29            |
| 30         | Restaurant/Tavern        | 0             |
| 60         | Coffee House             | 30            |
| 32         | Sports Bar               | 30            |
| 24         | Telecommunications       | 0             |
---------------------------------------------------------

我尝试了以下查询,但收到错误:

SELECT * FROM dbo.Category CAT 
ORDER BY (SELECT CategoryId FROM Category CAT2 WHERE CAT.CategoryId=CAT2.SubCategoryId), CategoryName

2 个答案:

答案 0 :(得分:1)

with cats as
 (select categoryname,
         categoryid,
         row_number() over(order by categoryname) as cat_rn
    from tbl
   where subcategoryid = 0)
select x.*
  from (select case
                 when c.cat_rn is null
                 then c2.categoryid
                 else t.categoryid
                  end as par,
               t.categoryid,
               t.categoryname,
               t.subcategoryid
          from tbl t
          left join cats c
            on t.categoryid = c.categoryid
          left join cats c2
            on t.subcategoryid = c2.categoryid) x
  join cats c
    on x.par = c.categoryid
 order by c.cat_rn,
          case when x.subcategoryid = 0 then '0' else x.categoryname end

<强>小提琴: http://sqlfiddle.com/#!3/548781/13/0

答案 1 :(得分:0)

试试这个:

SELECT cat.*
FROM dbo.Category CAT LEFT JOIN
     dbo.Category subcat
     ON cat.SubCateogryId = subcat.CategoryId
ORDER BY subcat.CategoryId,
          (case when subcat.CategoryId is null then 1 else 0 end) desc,
         CategoryName;

它加入子类别信息,但仅用于排序。