简体   繁体   中英

How can I add a sequence to the left of a materialized view in SQL?

I have a materialized view as follows:

|product_type|
--------------
shoes
clothing
electronics
..100's more

I'd like to create the view instead in a way that each product type has a corresponding ID. So the view should look as follows:

| ID | product_type|
--------------------
1   | shoes
2   | clothing
3   | electronics
100 | ..100's more

SQL used to create the view was:

select distinct(product_type) from items

You could use row_number() :

select row_number() over (order by product_type) as my_id

However, if you need a unique number per product_type -- and one that is stable over time -- I would suggest using an identity column in a "product types" table.

For your particular example, I would suggest:

select row_number() over (order by product_type), product_type
from items
group by product_type;

I think you need distinct product_type and then you want sequence number on it.

Use the following query:

Select product_type,
       row_number() over (order by product_type) row_num
  From (Select distinct product_type
          From items) t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM