如何排序sql查询

时间:2016-04-06 20:03:04

标签: sql sql-server

我有一组我要排名的结果:

我不确定要分区的是什么。

查询:

SELECT DISTINCT 
    TFormSectionID AS FormSectionID, 
    TFSSortOrder AS SectionSortOrder, 
    TSectionItemID AS SectionItemID, TrendType
FROM            
    Report.TrendData
WHERE        
    (ProgramID = 1) 
    AND (TrendType > 0) 
    AND tformid = 34 
    AND TFormSectionID = 12

结果:

FormSectionID   SectionSortOrder    SectionItemID   TrendType
    12                 7                  90            1
    12                 7                  91            1
    12                 7                  154           1
    12                 7                  528           1
    12                 9                  154           1
    12                 9                  528           1

我希望按部分排序顺序9的结果排名为2,部分排序顺序7排名为1

1 个答案:

答案 0 :(得分:1)

您似乎可以使用DENSE_RANK获得所需内容:

SELECT DISTINCT TFormSectionID AS FormSectionID, 
       TFSSortOrder AS SectionSortOrder, 
       TSectionItemID AS SectionItemID, 
       TrendType,
       DENSE_RANK() OVER (ORDER BY SectionSortOrder) AS rn       
FROM Report.TrendData
WHERE (ProgramID = 1) AND (TrendType > 0) AND 
      tformid = 34 and TFormSectionID = 12