如何根据数据更改排名

时间:2019-07-10 03:26:51

标签: sql amazon-redshift window-functions

我想有一个窗口函数,根据它们的值对月份进行排名。因此,在此示例中,2018-12为等级1,2019-01为2,依此类推。

我还希望在进入新的同类群组后重置排名计数器,在这种情况下,同类群组2的排名应再次从1开始,并且模式将类似于同类群组1。

SELECT *,
   rank() over (partition by cohort, month order by month asc)
FROM (
    SELECT 1 as cohort, id, date_trunc('month',start_date) as month
    FROM _analysis.terms
    WHERE holiday=FALSE and id >= 125 
    UNION SELECT 2, id, date_trunc('month', start_date) FROM _analysis.terms
    WHERE holiday=FALSE and id >= 126
    ORDER BY cohort, id, month
)
ORDER BY cohort, id, month

enter image description here

1 个答案:

答案 0 :(得分:0)

这可能会帮助

USE AdventureWorks2014
GO
SELECT SalesOrderID,OrderDate,DENSE_RANK() OVER(ORDER BY  MONTH(OrderDate) ASC) [Rank] 
FROM [Sales].[SalesOrderHeader]

enter image description here