如何根据年份和月份进行排名?
Posted
技术标签:
【中文标题】如何根据年份和月份进行排名?【英文标题】:How to make Ranking based on Year and Month? 【发布时间】:2019-12-06 10:52:09 【问题描述】:我正在尝试根据年份和月份放置排名。我有类似的记录
产品
ProdID Years Months Quantity
--------------------------------
1652 2018 10 2
1010 2018 9 2
2236 2018 10 2
2236 2018 10 2
1445 2019 5 2
1789 2019 12 2
1232 2018 12 2
我尝试了以下查询
SELECT
ProdID, Years, Months, Quantity,
DENSE_RANK()OVER (Partition By Years Order By Months) Ranks
FROM Products
显然,结果会是
ProdID Years Months Quantity Ranks
---------------------------------------
1010 2018 9 2 1
1652 2018 10 2 2
2236 2018 10 2 2
2236 2018 10 2 2
1232 2018 12 2 3
1445 2019 5 2 1
1789 2019 12 2 2
期待
ProdID Years Months Quantity Ranks
---------------------------------------
1010 2018 9 2 1
1652 2018 10 2 2
2236 2018 10 2 2
2236 2018 10 2 2
1232 2018 12 2 3
1232 2018 12 2 3
1445 2019 5 2 4
1789 2019 12 2 5
【问题讨论】:
【参考方案1】:您需要从查询中删除 partition by 子句。只需使用 order by 子句。
SELECT ProdID, Years, Months, Quantity,
DENSE_RANK()OVER (Order By Years, Months) Ranks
FROM Products
【讨论】:
正确的兄弟。还剩 5 分钟接受您的回答。谢谢你【参考方案2】:下面的查询应该做你想做的事:
SELECT
ProdID, Years, Months, Quantity,
DENSE_RANK()OVER (ORDER BY CAST(CAST(MONTHS AS VARCHAR)+'-01-'+CAST(YEARS AS VARCHAR) AS DATE)) Ranks
FROM Products
【讨论】:
以上是关于如何根据年份和月份进行排名?的主要内容,如果未能解决你的问题,请参考以下文章