2016-04-06 69 views
0

我有一組我想要排名的結果:如何對sql查詢進行排名

我不確定要劃分什麼內容。

查詢:

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

+0

按分節段劃分 –

+1

爲什麼你想得到你想要的結果的邏輯是什麼? –

回答

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 
+1

詳細闡述一下:窗口函數不需要*分區子句。沒有一個,它只是使用整個結果集作爲分區。 –