doupeng5320 2016-03-04 17:34
浏览 104

在PostgreSQL中使用Windows函数row_number()OVER()

I am looking at the documentation for row_number() but I don't understand what the use of this is. I have 2 queries which I am trying to join the results in to one table. Would using the windows function row_number() be useful in this condition. I need to understand the use of using this function. The documentation states that "number of the current row within its partition, counting from 1" but no example is given.

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-03-04 17:45
    关注

    ROW_NUMBER() OVER .. isn't going to help you with a JOIN. To join to tables, you use a JOIN in your FROM clause and the ON argument to specify the fields that are shared between the two tables being joined.

    As for ROW_NUMBER(), imagine you have a table like

    +-------+----------+
    | color |  animal  |
    +-------+----------+
    | red   | panda    |
    | red   | squirrel |
    | black | elephant |
    | black | squirrel |
    | black | panther  |
    | white | rabbit   |
    | white | cat      |
    | white | dog      |
    +-------+----------+
    

    If you wrote:

    SELECT
         color, animal, ROW_NUMBER() OVER (PARTITION BY color ORDER BY animal) as rownumber
    FROM myTable;
    

    You would get:

    +-------+----------+-----------+
    | color |  animal  | rownumber |
    +-------+----------+-----------+
    | red   | panda    |         1 |
    | red   | squirrel |         2 |
    | black | elephant |         1 |
    | black | squirrel |         3 |
    | black | panther  |         2 |
    | white | rabbit   |         3 |
    | white | cat      |         1 |
    | white | dog      |         2 |
    +-------+----------+-----------+
    

    What that did was "Partition" the records by color. Essentially making groups of animals by color. Then sorted each group by the Animal name. Then it numbered them, within their color partition starting at 1.

    I can't imagine that would help in a join but perhaps you have an oddball scenario where the two tables have no field-to-field relationship, so you have to rank the records and join on that rank? I hope not since that would be difficult, sketchy, and expensive.

    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据