简体   繁体   中英

Generate calculated column with row_number() over partition by

I want to generate a column containing a unique number based on state and number of times that has come up in database

It's like

Ny_1
Ny_2
St_1
Ny_3
St_2
Up_1
Ny_4

And so on...

I want a persisted calculated column

Other column must be like

Name   |  state   |  total    |  ticket no
Abc    |  Ny      |  1        |  Ny_1
Cda.   |  Ny      |  2        |  NY_2
Xyz.   |  St      |  1        |  ST_1

I can generate this in a view by using partition by and concatenate the result

But I am not sure if I can create a calculated column based on row_number() over (partition by something order by something)

Just 2-question

1) can I use partition in a calculated column

2) is there a better approach

(update from comments:)

Look the column that I am trying to generate will turn out to be the primary key...all the other column with be attached to it... It's business requirement... It has to be done this way only...

I have to generate a ticket number in database which should be like... State_number of tickets in the state_ this is the number all the database will be attached to.

It's an excel sheet I to convert to sql table... And it's the ticket number I am talking about...it has to be generated this way.

In Computed column we cannot use window functions, instead you can go for View

CREATE VIEW state_num
AS
  SELECT state,
         seq_state = state
                     + Cast(Row_number()OVER(partition BY state ORDER BY state) AS VARCHAR(50))
  FROM   yourtable 

If you are using SQL SERVER 2012 and above then use CONCAT function which does not require explicit conversion.

CREATE VIEW state_num
AS
  SELECT state,
         seq_state = Concat(state, Row_number()OVER(partition BY state ORDER BY state))
  FROM   yourtable 

Question 1 ) Can I use [window function with] partition [by] in a calculated column?

Answer : Yes, by using a function to return the value, but not persisted because it would be non-deterministic.

Question 2 ) Is there a better approach?

Answer : Yes, this should not be the primary key.

Why would you want this to be your primary key?

Saying that this is a business requirement doesn't make it a good idea. Find another way to accommodate your business requirements without them forcing you into horrible design decisions.

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