I have two tables as following.
'Areas' Table
| AreaKey | AreaID |
|-----------------|--------------|
| <identity/int> | <varchar> |
'Readings' Table
| ReadingKey | AreaKey | Reading | ReadingDateTime |
|-----------------|-------------------|-------------|----------------------|
| <identity/int> |<FK:AreaKey-Areas> | <float> | <datetime> |
Areas table already have some data with row id's ranging from 1 to 50.
I want to populate the Readings table with some sample data - (random float values for 'Reading' column between 1.0 and 100.0 AND a random datetime value for ReadingDateTime between a given DateTime range; for example between current datetime and a datetime 3 months back). These values should be inserted to the Reading table by randomly selecting AreaKeys which already exist in the Areas table.
In other words I want to insert random reading values to randomly selected areas, with random datetimes.
Can anyone give me a clue on how to do this?
Assuming your Areas table has 50 records, with row ids 1-50, I would just look into using the RAND function.
Something like this seems to work:
SELECT ROUND(((50 - 1 -1) * RAND() + 1), 0) as AreakKey,
ROUND(((100 - 1 -1) * RAND() + 1), 1) as Reading,
DATEADD(mm,-3,GETDATE()) +
(
ABS(
CAST(
CAST( NewID() AS BINARY(8) ) AS INT
)
)
%
CAST(
(GETDATE() - DATEADD(mm,-3,GETDATE())) AS INT
)
) as ReadingDateTime
And here's some SQL Fiddle.
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With