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.
-
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?Gary - Stand with Ukraine– Gary - Stand with Ukraine2015-08-05 07:13:59 +00:00Commented Aug 5, 2015 at 7:13
Add a comment
|
1 Answer
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