@@rowcount (transact-sql)@@rowcount (transact-sql)
Содержание:
Oracle ROW_NUMBER() examples
We’ll use the table from the sample database to demonstrate the function.
Oracle simple example
The following statement returns the row number, product name and list price from the table. The row number values are assigned based on the order of list prices.
The following picture shows the output:
This is a trivial example to just show how the function works.
To effectively use the function, you should use a subquery or a common table expression to retrieve row numbers for a specified range to get the top-N, bottom-N, and inner-N results.
Using Oracle function for pagination
The function is useful for pagination in applications.
Suppose you want to display products by pages with the list price from high to low, each page has 10 products. To display the third page, you use the function as follows:
The output is:
In this example, the CTE used the function to assign each row a sequential integer in descending order. The outer query retrieved the row whose row numbers are between 31 and 40.
Using Oracle function for the top-N query example
To get a single most expensive product by category, you can use the function as shown in the following query:
Here is the output:
In this example:
- First, the clause divided the rows into partitions by category id.
- Then, the clause sorted the products in each category by list prices in descending order.
- Next, the function is applied to each row in a specific category id. It re-initialized the row number for each category.
- After that, the outer query selected the rows with row number 1 which is the most expensive product in each category.
For the consistent result, the query must return a result set with the deterministic order. For example, if two products had the same highest prices, then the result would not be consistent. It could return the first or second product.
To get more than one product with the same N-highest prices, you can use the or function.
In this tutorial, you have learned how to use the Oracle function to make useful queries such as inner-N, top-N, and bottom-N.
- Was this tutorial helpful?
Using ROWNUM with Subqueries
A more appropriate way to use the ROWNUM pseudocolumn is with a subquery.
The basic steps are:
- Write your query
- Order your query
- Enclose this query within a subquery
- Filter the outer query using ROWNUM
Let’s see an example. Say we wanted to see the students who are in the top 5 when ordered by last_name.
One way to do this might be:
Result:
ROWNUM | FIRST_NAME | LAST_NAME | ADDRESS_STATE |
3 | Tom | Capper | Nevada |
4 | Mark | Holloway | New York |
2 | Susan | Johnson | Colorado |
1 | John | Smith | New York |
5 | Steven | Webber | New York |
However, this is not correct, because the ROWNUM is used to limit the number of rows, and then the ORDER BY is done. This shows the top 5 in the table before the ORDER BY.
To do this correctly, enclose it in a subquery as mentioned earlier.
Result:
ROWNUM | FIRST_NAME | LAST_NAME | ADDRESS_STATE |
1 | Mark | Anderson | California |
2 | Julie | Armstrong | Texas |
3 | Tom | Capper | Nevada |
4 | Andrew | Cooper | Texas |
5 | Tanya | Hall | Texas |
This now shows the student records, ordered by last_name, and then only the top 5, which is the result we were looking for.
So, that’s what Oracle ROWNUM and Oracle ROW_NUMBER does, and how they are different. Be careful when you use the ORDER BY as well, as it may not give you the results you need.
Lastly, if you enjoy the information and career advice I’ve been providing, sign up to my newsletter below to stay up-to-date on my articles. You’ll also receive a fantastic bonus. Thanks!
参数Arguments
PARTITION BY value_expression PARTITION BY value_expression将 FROM 子句生成的结果集划分为应用 ROW_NUMBER 函数的分区。Divides the result set produced by the FROM clause into partitions to which the ROW_NUMBER function is applied. value_expression 指定对结果集进行分区所依据的列 。value_expression specifies the column by which the result set is partitioned. 如果未指定 ,则此函数将查询结果集的所有行视为单个组。If is not specified, the function treats all rows of the query result set as a single group. 有关详细信息,请参阅 OVER 子句 (Transact-SQL)。For more information, see OVER Clause (Transact-SQL).
order_by_clause order_by_clause 子句可确定在特定分区中为行分配唯一 的顺序。The clause determines the sequence in which the rows are assigned their unique within a specified partition. 它是必需的。It is required. 有关详细信息,请参阅 OVER 子句 (Transact-SQL)。For more information, see OVER Clause (Transact-SQL).
Example
Let’s look at some Oracle ROWNUM function examples and explore how to use the ROWNUM function in Oracle/PLSQL.
In this ROWNUM example, we have a table called customers with the following data:
CUSTOMER_ID LAST_NAME FIRST_NAME FAVORITE_WEBSITE ----------- --------- ---------- --------------------- 4000 Jackson Joe www.techonthenet.com 5000 Smith Jane www.digminecraft.com 6000 Ferguson Samantha www.bigactivities.com 7000 Reynolds Allen www.checkyourmath.com 8000 Anderson Paige 9000 Johnson Derek www.techonthenet.com
Now let’s demonstrate how the ROWNUM function works by selecting data from the customers table. Enter the following SQL statement in Oracle:
SELECT ROWNUM, customers.* FROM customers WHERE customer_id > 4500;
These are the results that you should see:
ROWNUM CUSTOMER_ID LAST_NAME FIRST_NAME FAVORITE_WEBSITE ------ ----------- --------- ---------- --------------------- 1 5000 Smith Jane www.digminecraft.com 2 6000 Ferguson Samantha www.bigactivities.com 3 7000 Reynolds Allen www.checkyourmath.com 4 8000 Anderson Paige 5 9000 Johnson Derek www.techonthenet.com
In this example, the ROWNUM function returns 1 for the first record, 2 for the second record, and so on. Since this is a very simple example, it would appear that the ROWNUM function is straight-forward to use, but it is a bit more complicated than you think.
Let’s complicate the example by introducing an ORDER BY clause and sort the results by last_name in ascending order. Enter the following SELECT statement in Oracle:
SELECT ROWNUM, customers.* FROM customers WHERE customer_id > 4500 ORDER BY last_name;
You should see these results:
ROWNUM CUSTOMER_ID LAST_NAME FIRST_NAME FAVORITE_WEBSITE ------ ----------- --------- ---------- --------------------- 4 8000 Anderson Paige 2 6000 Ferguson Samantha www.bigactivities.com 5 9000 Johnson Derek www.techonthenet.com 3 7000 Reynolds Allen www.checkyourmath.com 1 5000 Smith Jane www.digminecraft.com
You would expect that the first row in your result set would have a ROWNUM value of 1, but in this example, it has a ROWNUM value of 4. Why is this? Well, it depends how Oracle accessed the rows in the query. For example your results can vary depending on a lot of factors (ie: the order that you inserted the data in the table or if there is an index on the table).
Because of these factors, there is a right and wrong way to use the ROWNUM function.
Recommended Way to Use ROWNUM
The most reliable way to use the ROWNUM is to use a subquery to filter and sort your results and then place the ROWNUM function in the outer SELECT. Enter the following SELECT in Oracle:
SELECT ROWNUM, a.* FROM (SELECT customers.* FROM customers WHERE customer_id > 4500 ORDER BY last_name) a;
These are the results that you should see:
ROWNUM CUSTOMER_ID LAST_NAME FIRST_NAME FAVORITE_WEBSITE ------ ----------- --------- ---------- --------------------- 1 8000 Anderson Paige 2 6000 Ferguson Samantha www.bigactivities.com 3 9000 Johnson Derek www.techonthenet.com 4 7000 Reynolds Allen www.checkyourmath.com 5 5000 Smith Jane www.digminecraft.com
By using a subquery in this way, it forces the ROWNUM to properly order the records, starting at 1 for the first record, 2 for the second and so on.
Use ROWNUM to Limit Results
The ROWNUM function is also handy if you want to limit the results of a query. For example, you could return the top 2 results. Enter the following SQL statement in Oracle:
SELECT * FROM (SELECT customers.* FROM customers WHERE customer_id > 4500 ORDER BY last_name) WHERE ROWNUM < 3;
You should see these results:
CUSTOMER_ID LAST_NAME FIRST_NAME FAVORITE_WEBSITE ----------- --------- ---------- --------------------- 8000 Anderson Paige 6000 Ferguson Samantha www.bigactivities.com
In this example, the ROWNUM function would return the top 2 results because we want .
If we wanted to get the bottom 2 results, we could just change the sort order of the subquery to . Enter the following query in Oracle:
SELECT * FROM (SELECT customers.* FROM customers WHERE customer_id > 4500 ORDER BY last_name DESC) WHERE ROWNUM < 3;
These are the results that you should see:
CUSTOMER_ID LAST_NAME FIRST_NAME FAVORITE_WEBSITE ----------- --------- ---------- ------------------- 5000 Smith Jane www.digminecraft.com 7000 Reynolds Allen www.checkyourmath.com
Now we get the bottom 2 results because we have sorted the last_name in descending order.
ROW_NUMBER Analytic Function
If you have ever used the pseudocolumn, you will have an idea what the analytic function does. It is used to assign a unique number from 1-N to the rows within a partition. At first glance this may seem similar to the RANK and DENSE_RANK analytic functions, but the function ignores ties and always gives a unique number to each row.
The basic description for the analytic function is shown below. The analytic clause is described in more detail .
ROW_NUMBER() OVER ( order_by_clause)
The analytic function is order-sensitive and produces an error if you attempt to use it without an in the analytic clause. Unlike some other analytic functions, it doesn’t support the windowing clause. Omitting a partitioning clause from the clause means the whole result set is treated as a single partition. In the following example we assign a unique row number to each employee based on their salary (lowest to highest). The example also includes and to show the difference in how ties are handled.
SELECT empno, ename, deptno, sal, ROW_NUMBER() OVER (ORDER BY sal) AS row_num, RANK() OVER (ORDER BY sal) AS row_rank, DENSE_RANK() OVER (ORDER BY sal) AS row_dense_rank FROM emp; EMPNO ENAME DEPTNO SAL ROW_NUM ROW_RANK ROW_DENSE_RANK ---------- ---------- ---------- ---------- ---------- ---------- -------------- 7369 SMITH 20 800 1 1 1 7900 JAMES 30 950 2 2 2 7876 ADAMS 20 1100 3 3 3 7521 WARD 30 1250 4 4 4 7654 MARTIN 30 1250 5 4 4 7934 MILLER 10 1300 6 6 5 7844 TURNER 30 1500 7 7 6 7499 ALLEN 30 1600 8 8 7 7782 CLARK 10 2450 9 9 8 7698 BLAKE 30 2850 10 10 9 7566 JONES 20 2975 11 11 10 7788 SCOTT 20 3000 12 12 11 7902 FORD 20 3000 13 12 11 7839 KING 10 5000 14 14 12 SQL>
Adding the partitioning clause allows us to assign the row number within a partition. In the following example we assign the row number within the department, based on highest to lowest salary.
SELECT empno, ename, deptno, sal, ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY sal DESC) AS row_num FROM emp; EMPNO ENAME DEPTNO SAL ROW_NUM ---------- ---------- ---------- ---------- ---------- 7839 KING 10 5000 1 7782 CLARK 10 2450 2 7934 MILLER 10 1300 3 7788 SCOTT 20 3000 1 7902 FORD 20 3000 2 7566 JONES 20 2975 3 7876 ADAMS 20 1100 4 7369 SMITH 20 800 5 7698 BLAKE 30 2850 1 7499 ALLEN 30 1600 2 7844 TURNER 30 1500 3 7654 MARTIN 30 1250 4 7521 WARD 30 1250 5 7900 JAMES 30 950 6 SQL>
This allows us to write Top-N queries at the partition level. The following example brings back the best paid person in each department, ignoring ties.
SELECT * FROM (SELECT empno, ename, deptno, sal, ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY sal DESC) AS row_num FROM emp) WHERE row_num = 1; EMPNO ENAME DEPTNO SAL ROW_NUM ---------- ---------- ---------- ---------- ---------- 7839 KING 10 5000 1 7788 SCOTT 20 3000 1 7698 BLAKE 30 2850 1 SQL>
Setup
The examples in this article require the following table.
--DROP TABLE emp PURGE; CREATE TABLE emp ( empno NUMBER(4) CONSTRAINT pk_emp PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4), hiredate DATE, sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(2) ); INSERT INTO emp VALUES (7369,'SMITH','CLERK',7902,to_date('17-12-1980','dd-mm-yyyy'),800,NULL,20); INSERT INTO emp VALUES (7499,'ALLEN','SALESMAN',7698,to_date('20-2-1981','dd-mm-yyyy'),1600,300,30); INSERT INTO emp VALUES (7521,'WARD','SALESMAN',7698,to_date('22-2-1981','dd-mm-yyyy'),1250,500,30); INSERT INTO emp VALUES (7566,'JONES','MANAGER',7839,to_date('2-4-1981','dd-mm-yyyy'),2975,NULL,20); INSERT INTO emp VALUES (7654,'MARTIN','SALESMAN',7698,to_date('28-9-1981','dd-mm-yyyy'),1250,1400,30); INSERT INTO emp VALUES (7698,'BLAKE','MANAGER',7839,to_date('1-5-1981','dd-mm-yyyy'),2850,NULL,30); INSERT INTO emp VALUES (7782,'CLARK','MANAGER',7839,to_date('9-6-1981','dd-mm-yyyy'),2450,NULL,10); INSERT INTO emp VALUES (7788,'SCOTT','ANALYST',7566,to_date('13-JUL-87','dd-mm-rr')-85,3000,NULL,20); INSERT INTO emp VALUES (7839,'KING','PRESIDENT',NULL,to_date('17-11-1981','dd-mm-yyyy'),5000,NULL,10); INSERT INTO emp VALUES (7844,'TURNER','SALESMAN',7698,to_date('8-9-1981','dd-mm-yyyy'),1500,0,30); INSERT INTO emp VALUES (7876,'ADAMS','CLERK',7788,to_date('13-JUL-87', 'dd-mm-rr')-51,1100,NULL,20); INSERT INTO emp VALUES (7900,'JAMES','CLERK',7698,to_date('3-12-1981','dd-mm-yyyy'),950,NULL,30); INSERT INTO emp VALUES (7902,'FORD','ANALYST',7566,to_date('3-12-1981','dd-mm-yyyy'),3000,NULL,20); INSERT INTO emp VALUES (7934,'MILLER','CLERK',7782,to_date('23-1-1982','dd-mm-yyyy'),1300,NULL,10); COMMIT;
PostgreSQL ROW_NUMBER() function examples
We will use the table created in the PostgreSQL window function tutorial to demonstrate the functionality of the function.
The following is the data in the table:
See the following query.
Because we did not use the clause, the function considers the whole result set as a partition.
The clause sorts the result set by , therefore, the function assigns integer values to the rows based on the order.
In the following query, we change the column in the clause to product_name, the function assigns the integer values to each row based on the product name order.
In the following query, we use the clause to divide the window into subsets based on the values in the column. In this case, the function assigns one to the starting row of each partition and increases by one for the next row within the same partition.
The clause sorts the rows in each partition by the values in the column.
MySQL ROW_NUMBER() function examples
Let’s use the table from the sample database for the demonstration:
1) Assigning sequential numbers to rows
The following statement uses the function to assign a sequential number to each row from the table:
Here is the output:
2) Finding top N rows of every group
You can use the function for the queries that find the top N rows for every group, for example, top three sales employees of every sales channel, top five high-performance products of every category.
The following statement finds the top three products that have the highest inventory of every product line:
In this example,
- First, we used the function to rank the inventory of all products in each product line by partitioning all products by product line and ordering them by quantity in stock in descending order. As the result, each product is assigned a rank based on its quantity in stock. and the rank is reset for each product line.
- Then, we selected only products whose rank is less than or equal to three.
The following shows the output:
3) Removing duplicate rows
You can use the to turn non-unique rows into unique rows and then delete the duplicate rows. Consider the following example.
First, create a table with some duplicate values:
Second, use the function to divide the rows into partitions by all columns. The row number will restart for each unique set of rows.
As you can see from the output, the unique rows are the ones whose the row number equals one.
Third, you can use the common table expression (CTE) to return the duplicate rows and delete statement to remove:
Notice that the MySQL does not support CTE based delete, therefore, we had to join the original table with the CTE as a workaround.
4) Pagination using function
Because the assigns each row in the result set a unique number, you can use it for pagination.
Suppose, you need to display a list of products with 10 products per page. To get the products for the second page, you use the following query:
Here is the output:
In this tutorial, you have learned how to use the MySQL function to generate a sequential number for each row in a result set.
- Was this tutorial helpful?
Команды для создания запросов
13. SELECT
используется для получения данных из определённой таблицы:
Следующей командой можно вывести все данные из таблицы:
14. SELECT DISTINCT
В столбцах таблицы могут содержаться повторяющиеся данные. Используйте для получения только неповторяющихся данных.
15. WHERE
Можно использовать ключевое слово в для указания условий в запросе:
В запросе можно задавать следующие условия:
- сравнение текста;
- сравнение численных значений;
- логические операции AND (и), OR (или) и NOT (отрицание).
Попробуйте выполнить следующие команды
Обратите внимание на условия, заданные в :
16. GROUP BY
Оператор часто используется с агрегатными функциями, такими как , , , и , для группировки выходных значений.
Выведем количество курсов для каждого факультета:
17. HAVING
Ключевое слово было добавлено в SQL потому, что не может быть использовано для работы с агрегатными функциями.
Выведем список факультетов, у которых более одного курса:
18. ORDER BY
используется для сортировки результатов запроса по убыванию или возрастанию. отсортирует по возрастанию, если не будет указан способ сортировки или .
Выведем список курсов по возрастанию и убыванию количества кредитов:
19. BETWEEN
используется для выбора значений данных из определённого промежутка. Могут быть использованы числовые и текстовые значения, а также даты.
Выведем список инструкторов, чья зарплата больше 50 000, но меньше 100 000:
20. LIKE
Оператор используется в , чтобы задать шаблон поиска похожего значения.
Хакатон Tour.Hack
Ивент перенесён на 26–27 сентября, Новосибирск, беcплатно
tproger.ru
События и курсы на tproger.ru
Есть два свободных оператора, которые используются в :
- (ни одного, один или несколько символов);
- (один символ).
Выведем список курсов, в имени которых содержится , и список курсов, название которых начинается с :
21. IN
С помощью можно указать несколько значений для оператора :
Выведем список студентов с направлений Comp. Sci., Physics и Elec. Eng.:
22. JOIN
используется для связи двух или более таблиц с помощью общих атрибутов внутри них. На изображении ниже показаны различные способы объединения в SQL
Обратите внимание на разницу между левым внешним объединением и правым внешним объединением:
Выведем список всех курсов вне зависимости от того, обязательны они или нет:
23. View
— это виртуальная таблица SQL, созданная в результате выполнения выражения. Она содержит строки и столбцы и очень похожа на обычную SQL-таблицу. всегда показывает самую свежую информацию из базы данных.
Создадим , состоящую из курсов с 3 кредитами:
24. Агрегатные функции
Эти функции используются для получения совокупного результата, относящегося к рассматриваемым данным. Ниже приведены общеупотребительные агрегированные функции:
- — возвращает количество строк;
- — возвращает сумму значений в данном столбце;
- — возвращает среднее значение данного столбца;
- — возвращает наименьшее значение данного столбца;
- — возвращает наибольшее значение данного столбца.
SQL ROW_NUMBER() Function Overview
The is a window function that assigns a sequential integer number to each row in the query’s result set.
The following illustrates the syntax of the function:
In this syntax,
- First, the clause divides the result set returned from the clause into partitions. The clause is optional. If you omit it, the whole result set is treated as a single partition.
- Then, the clause sorts the rows in each partition. Because the is an order sensitive function, the clause is required.
- Finally, each row in each partition is assigned a sequential integer number called a row number. The row number is reset whenever the partition boundary is crossed.
ПримерыExamples
A.A. Простые примерыSimple examples
Приведенный ниже запрос возвращает четыре системные таблицы в алфавитном порядке.The following query returns the four system tables in alphabetic order.
Результирующий набор:Here is the result set.
namename | recovery_model_descrecovery_model_desc |
---|---|
mastermaster | ПРОСТОЙSIMPLE |
modelmodel | FULLFULL |
msdbmsdb | ПРОСТОЙSIMPLE |
tempdbtempdb | ПРОСТОЙSIMPLE |
Чтобы добавить столбец с номерами строк перед каждой строкой, добавьте столбец с помощью функции , в данном случае с именем .To add a row number column in front of each row, add a column with the function, in this case named . Предложение необходимо переместить к предложению .You must move the clause up to the clause.
Результирующий набор:Here is the result set.
Номер строкиRow# | namename | recovery_model_descrecovery_model_desc |
---|---|---|
11 | mastermaster | ПРОСТОЙSIMPLE |
22 | modelmodel | FULLFULL |
33 | msdbmsdb | ПРОСТОЙSIMPLE |
44 | tempdbtempdb | ПРОСТОЙSIMPLE |
Добавление предложения для столбца приведет к тому, что нумерация начнется заново при изменении значения .Adding a clause on the column, will restart the numbering when the value changes.
Результирующий набор:Here is the result set.
Номер строкиRow# | namename | recovery_model_descrecovery_model_desc |
---|---|---|
11 | modelmodel | FULLFULL |
11 | mastermaster | ПРОСТОЙSIMPLE |
22 | msdbmsdb | ПРОСТОЙSIMPLE |
33 | tempdbtempdb | ПРОСТОЙSIMPLE |
Б.B. Возврат номера строки для salespeopleReturning the row number for salespeople
В следующем примере показан расчет номера строки для salespeople в Компания Adventure Works CyclesAdventure Works Cycles, выполняемый на основе ранжирования продаж за текущий год.The following example calculates a row number for the salespeople in Компания Adventure Works CyclesAdventure Works Cycles based on their year-to-date sales ranking.
Результирующий набор:Here is the result set.
В.C. Возврат подмножества строкReturning a subset of rows
В следующем примере показан расчет номеров всех строк в таблице в порядке с последующим возвращением строк с номерами от до включительно.The following example calculates row numbers for all rows in the table in the order of the and returns only rows to inclusive.
Г.D. Использование ROW_NUMBER() с PARTITIONUsing ROW_NUMBER() with PARTITION
В следующем примере аргумент используется для секционирования результирующего набора запроса по столбцу .The following example uses the argument to partition the query result set by the column . Предложение , указанное в предложении , упорядочивает строки каждой секции по столбцу .The clause specified in the clause orders the rows in each partition by the column . Предложение в инструкции упорядочивает полный результирующий набор запроса по .The clause in the statement orders the entire query result set by .
Результирующий набор:Here is the result set.
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
Пример
Рассмотрим пример Oracle, чтобы понять, как применять %ROWTYPE в Oracle PL/SQL. Например:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
DECLARE emp_recemployees%ROWTYPE; CURSORc1IS SELECTdepartment_id,department_nameFROMdepartments; dept_recc1%ROWTYPE; CURSORc2IS SELECTemployee_id,email,employees.manager_id,location_id FROMemployees,departments WHEREemployees.department_id=departments.department_id; join_recc2%ROWTYPE; SELECT*INTOemp_recFROMemployeesWHEREROWNUM<2; IFemp_rec.department_id=20ANDemp_rec.last_name=’JOHNSON’THEN emp_rec.salary:=emp_rec.salary*1.15; ENDIF; END; |
В этом примере Oracle PL/SQL мы объявили переменную emp_rec основанную на записи таблицы employees. Также мы объявили переменную join_rec основанную на записи курсора c2 созданного из полей таблиц employees и departments.