简体   繁体   English

查询以获取一列的最高ROW_NUM()值,仅获得另一列的RANK()值

[英]Query to get highest ROW_NUM() value of a column AS only RANK() value of another column

It's question #105 on http://sql-ex.ru http://sql-ex.ru上的问题#105

This is the database schema : 这是数据库模式: 数据库架构

The question : Statisticians Alice, Betty, Carol and Diana are numbering rows in the Product table. 问题:统计学家Alice,Betty,Carol和Diana正在对Product表中的行进行编号。 Initially all they have sorted the table rows in ascending order of the makers' names. 最初,他们都是按照制造者名称的升序对表格行进行排序。 Alice is assigning a new number to each row, in so doing she is ordering the rows of the same maker by model ascending. 爱丽丝正在为每行分配一个新的编号,这样做是按照型号升序对同一制造商的行进行排序。 Three other statisticians are assigning the identical number to all rows of the same maker. 另外三位统计员将相同的编号分配给同一制造商的所有行。

  • Betty assigns the numbers starting from one, every next maker increases the number by 1. Betty从1开始分配数字,每个下一个制造商将数字增加1。

  • Carol gives such number to a maker, which number Alice would give for the first model of this maker. 卡罗尔将这个编号提供给制造商,而爱丽丝将为该制造商的第一个型号提供该编号。

  • Diana gives such number to a maker, which number Alice would give for the last model of this maker. 戴安娜(Diana)将这个编号提供给制造商,爱丽丝(Alice)将为该制造商的最后一个型号提供该编号。

Output: maker, model, numbers which have been assigned to the table rows by Alice, Betty, Carol, and Diana respectively. 输出:制造商,型号,编号,分别由Alice,Betty,Carol和Diana分配给表行。

I came up with this query already for Alice(A),Betty(B),Carol(C) 我已经针对Alice(A),Betty(B),Carol(C)提出了此查询

SELECT maker, model, 
 ROW_NUMBER() OVER (ORDER BY maker,model ASC) A,
 DENSE_RANK() OVER(ORDER BY maker) B,
 RANK() OVER (ORDER BY maker) C
 FROM product
 ORDER BY model ASC

But I'm having trouble finding the solution for Diana(D) Column. 但是我很难找到Diana(D)色谱柱的解决方案。

According to the site, this is the result a correct query should give : 根据站点,这是正确查询应给出的结果: 正确查询应给出的结果

Thanks for your help, time and comprehension. 感谢您的帮助,时间和理解。

SELECT 
       (SELECT COUNT(*)
        FROM product T2
        WHERE T2.[maker] <= T1.[maker]) as D
FROM product T1

See example 例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM