Suppose I have a table:
HH SLOT RN
--------------
1 1 null
1 2 null
1 3 null
--------------
2 1 null
2 2 null
2 3 null
I want to set RN to be a random number between 1 and 10. It's ok for the number to repeat across the entire table, but it's bad to repeat the number within any given HH. E.g.,:
HH SLOT RN_GOOD RN_BAD
--------------------------
1 1 9 3
1 2 4 8
1 3 7 3 <--!!!
--------------------------
2 1 2 1
2 2 4 6
2 3 9 4
This is on Netezza if it makes any difference. This one's being a real headscratcher for me. Thanks in advance!
I am not an expert on SQL, but probably do something like this:
Well, I couldn't get a slick solution, so I did a hack:
rand_inst
.rand_inst
to be the instance number of that random number within this household. E.g., if I get two 3's, then the second 3 will haverand_inst
set to 2.rand_inst>1
.Here's what it looks like. Too lazy to anonymise it, so the names are a little different from my original post:
To get a random number between 1 and the number of rows in the hh, you can use:
The larger range of values is a bit more challenging. The following calculates a table (called
randoms
) with numbers and a random position in the same range. It then usesslot
to index into the position and pull the random number from therandoms
table:Here is a SQLFiddle that demonstrates this in Postgres, which I assume is close enough to Netezza to have matching syntax.