Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - how to determine which position/order/count my selected record is in?

Imagine I have a table:

ID     field1       field2
---    -------      ------
111      1          11113
112      1          11114
113      1          44321
114      1          49339
115      2          53234

I'm interested in all records where field1 = 1 - and specifically field2 = 44321 , but I want to know what position it is in my selection of field1=1 (in this case, it'd be 3).

 SELECT * FROM table WHERE field1 = 1 ORDER BY id

will get me all the records I want, but what I want to know is the number 3 (the position in the selection that 44321 is - it's the 3rd record in the query, I want to know that 3).

Is there any elegant query I can do to find out the position of the row I'm particularly interested in, or do I need to cursor fetch and walk through my recordset and find out with some counter++ business?

I know the field1 I want, I know the field2 I want - I just want to know what position field1+field2 is in the greater field1=1 query - that 3, the position).

like image 683
Jason Avatar asked Jun 03 '11 16:06

Jason


People also ask

How do I use count by order in SQL?

Use ORDER BY with DESC to order in descending order. For counting the values, use the COUNT(). For example, if the name “John” appears thrice in the column, then a separate column will display the count 3 and in this way all the count values will be arranged in descending order using the ORDER BY DESC.

How do I count a selected record in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

Can we use count with ORDER BY?

For uninitiated, a COUNT() function is used to find the total number of records in the result set. It is usually used in combination with the GROUP BY clause to prepare a summary of the total number of records in each group. It can further be used with ORDER BY clause to sort the obtained summary table.

Which is the correct order in SQL query?

The correct answer is Select, where, group by, having.


2 Answers

Try this:

POS column will give the position of the record that you are looking for

WITH qry AS
(
    SELECT a.* 
                 ROW_NUMBER() OVER(ORDER BY id)  POS
        FROM table a
     WHERE field1 = 1 
)
SELECT qry.pos
  FROM qry
 WHERE field2 = 44321 
like image 97
Chandu Avatar answered Oct 03 '22 09:10

Chandu


SELECT COUNT(*)+1
FROM table
WHERE ID<(SELECT TOP 1 ID
          FROM table
          WHERE field1=1
          AND field2=44321)
like image 35
Curtis Avatar answered Oct 01 '22 09:10

Curtis