【问题标题】:How to change rank according to data changes如何根据数据变化改变排名
【发布时间】:2019-11-19 15:03:50
【问题描述】:

我想要一个窗口函数来根据它们的值对月份进行排名。所以在这个例子中,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

【问题讨论】:

    标签: sql amazon-redshift window-functions


    【解决方案1】:

    这可能会有所帮助

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

    【讨论】:

    • 非常感谢!!!拯救了我的一天。为什么在这种情况下密集排名不会将两个相同的订单日期分配为两个单独的排名?
    • 它是按月份而不是按日期排序的。 MONTH('date') 返回指定日期的月份。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多