0

I have table in postgresql with statename, districtname and DistID . Now I want to assign random number(starting from 1 to count of district in a particular state) to the column 'DistID' for each district based on their states. Kindly help.

1
  • Do the numbers need to be unique within a particular state, and when you say random do you mean they need to be unpredictable or you just don't care what the numbers are? Commented Aug 5, 2015 at 7:13

1 Answer 1

1

The query below will update the table so that each district is numbered within the state with values starting from 1.

The query assigns the IDs in a random order. If you wanted predictable change random() to district and it will order them by district name alphabetically.

update t
set distid = v.distid
from (
select 
  statename, district, 
  row_number() over (partition by statename order by random()) as distid
from t) v
where v.statename = t.statename and v.district = t.district;

Fiddle example at http://sqlfiddle.com/#!15/86341/5

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.