Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values alternate for ROW_NUMBER()?

I have a table with values like these:

Name    Order    Innings
Suresh    1         1
Ramesh    2         1
Sekar     3         1
Raju      1         2
Vinoth    2         2
Ramu      3         2

I want the result be like this:

1stInn  2ndInn  Order
Suresh  Raju      1
Ramesh  Vinoth    2
Sekar   Ramu      3

I got the result using ROW_NUMBER() in SQL Server.

I want the same result in SQL Compact, But I can't use ROW_NUMBER() in SQL Compact.

I'm using SQL Compact version - 4.0.8482.1

How can I get the result?

like image 830
DineshDB Avatar asked Jun 01 '16 08:06

DineshDB


People also ask

Can ROW_NUMBER be used without ORDER BY?

The row_number() window function can be used without order by in over to arbitrarily assign a unique value to each row.

What is the equivalent of Rownum in MySQL?

MySQL doesn't support ROWNUM() function, but it since version 8.0, MySQL introduced ROW_NUMBER() function as an equivalent to return the number of the current row within its partition during data retrieval. Rows numbers range from 1 to the number of rows in the partition.

Can you use ROW_NUMBER in WHERE clause?

The ROW_NUMBER function cannot currently be used in a WHERE clause. Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery.

How do I display row numbers with records in SQL?

Here is the result set. To add a row number column in front of each row, add a column with the ROW_NUMBER function, in this case named Row# . You must move the ORDER BY clause up to the OVER clause. SELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.


Video Answer


2 Answers

Why do you need ROW_NUMBER()? you can use conditional aggregation using CASE EXPRESSION :

SELECT MAX(CASE WHEN t.innings = 1 THEN t.name END) as 1stInn,
       MAX(CASE WHEN t.innings = 2 THEN t.name END) as 2sndInn,
       t.Order
FROM YourTable t
GROUP BY t.order
like image 198
sagi Avatar answered Oct 21 '22 11:10

sagi


simple Pivot will give the similar result

DECLARE @Table1  TABLE 
    ( Name  varchar(6),  [Order]  int,  Innings  int)
;

INSERT INTO @Table1
    ( Name ,  [Order] ,  Innings )
VALUES
    ('Suresh', 1, 1),
    ('Ramesh', 2, 1),
    ('Sekar', 3, 1),
    ('Raju', 1, 2),
    ('Vinoth', 2, 2),
    ('Ramu', 3, 2)
;
select [1] AS '1stinn',[2] AS '2ndinn',[order] from(
select Name ,  [Order] ,  Innings from  @Table1)T
PIVOT (MAX(NAME) FOR Innings IN ([1],[2]))PVT
like image 37
mohan111 Avatar answered Oct 21 '22 11:10

mohan111