列结果为ROW_NUMBER

时间:2015-05-15 17:11:46

标签: sql sql-server tsql window-functions

如何计算给定列中的出现次数?

请按照此示例操作。有这样一个表:

+----------+---------+------+
| PersonID |  Name   | City |
+----------+---------+------+
|        1 | John    | NY   |
|        2 | Mohit   | CA   |
|        3 | Jay     | AZ   |
|        4 | Roger   | NY   |
|        5 | David   | NY   |
|        6 | Peter   | AZ   |
|        7 | Ana     | NY   |
|        8 | Irina   | NY   |
|        9 | Michael | NY   |
|       10 | Ken     | AZ   |
+----------+---------+------+

我怎样才能做到这一点?

+----------+---------+------+-------------+
| PersonID |  Name   | City | CityCounter |
+----------+---------+------+-------------+
|        1 | John    | NY   |           1 |
|        2 | Mohit   | CA   |           1 |
|        3 | Jay     | AZ   |           1 |
|        4 | Roger   | NY   |           2 |
|        5 | David   | NY   |           3 |
|        6 | Peter   | AZ   |           2 |
|        7 | Ana     | NY   |           4 |
|        8 | Irina   | NY   |           5 |
|        9 | Michael | NY   |           6 |
|       10 | Ken     | AZ   |           3 |
+----------+---------+------+-------------+

我是否必须使用ROW_NUMBER函数而不是SUM?

3 个答案:

答案 0 :(得分:3)

就这么简单。

SELECT *,
       cityCounter = ROW_NUMBER() OVER (PARTITION BY city ORDER BY personID)
FROM yourTable
ORDER BY personID

答案 1 :(得分:1)

如果我理解正确,您只想枚举每个城市的值,然后按id排序:

select t.*
from (select t.*,
             row_number() over (partition by city
                                order by personid) as CityCounter
      from table t
     ) t
order by personid;

答案 2 :(得分:1)

您可以使用row_number()分析函数来实现结果,但是没有过SUM? 您可以阅读有关使用row_number()及其正确语法的http://ashken-f00fc7c8.rhcloud.com/webservice/文档。

在您的情况下,您想要对每个城市的出现次数进行编号,这意味着您需要按城市进行分组(按城市划分),然后您需要为您的订购提供逻辑,哪个城市线应该是第一个,是它当personID出现时?

您的row_number将如下所示:

return allDashboardsDeferred;