Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add ROW_NUMBER() in a view?

In PostgreSQL 8.4 I want to create a view from 3 tables with id. So I want to have this structure in my view:

num serial,
name_dispatcher character varying(250)
the_geom geometry

I can select name_dispatcher and the_geom from tables:

 CREATE VIEW lineView
      AS SELECT 'name' AS name_dispatcher, the_geom
      FROM line1
      UNION
      SELECT 'name' AS name_dispatcher, the_geom
      FROM line2
      UNION
      SELECT 'name' AS name_dispatcher, the_geom
      FROM line3

How to create the num column in the view?

UPDATE

I found a solution:

ROW_NUMBER() OVER(ORDER BY lineView.voltage)

But I don't know how to use it in ALTER VIEW. How do I put it in there?

like image 211
Kliver Max Avatar asked Jan 18 '13 07:01

Kliver Max


People also ask

Is ROW_NUMBER () available in MySQL?

The ROW_NUMBER() function in MySQL is used to returns the sequential number for each row within its partition. It is a kind of window function. The row number starts from 1 to the number of rows present in the partition.

Can you use ROW_NUMBER in access?

You can use any field that will be in the query output as the input for RowNum and GetRowNum . Important to note is to only use RowNum for the first time you want the row number and use GetRowNum every time after. This is to prevent one row increasing the counter more than once.


1 Answers

You can't use ALTER VIEW to drop or add columns. I quote the manual on ALTER VIEW:

ALTER VIEW changes various auxiliary properties of a view. (If you want to modify the view's defining query, use CREATE OR REPLACE VIEW.)

But a simple CREATE OR REPLACE VIEW won't cut it. Another quote from the manual:

The new query must generate the same columns that were generated by the existing view query

So DROP and CREATE the view:

DROP VIEW lineview;

CREATE VIEW lineview AS
SELECT *, row_number() OVER(ORDER BY ???) AS num
FROM (
   SELECT 'name' AS name_dispatcher, the_geom
   FROM line1

   UNION
   SELECT 'name' AS name_dispatcher, the_geom
   FROM line2

   UNION
   SELECT 'name' AS name_dispatcher, the_geom
   FROM line3
   ) x

I use a subquery because I assume you want to add row_number() to all rows. Your question is vague in that respect.
If you just want a unique id in no particular order, use row_number() OVER().

like image 75
Erwin Brandstetter Avatar answered Oct 01 '22 17:10

Erwin Brandstetter