在Sql中生成随机值

时间:2016-05-11 22:12:23

标签: sql database sqlite

我想每个月从德国,加拿大,巴西三个国家/地区挑选一位客户(表名为国家/地区)。我需要生成他们的名字和姓名,这是在另一个名为“customer”的表中。我有这个想法开始,但如果我在正确的轨道上不是100%。

SELECT DISTINCT CountryID
FROM Country
WHERE CountryName IN('Germany','Canada','Brazil')


Country ID  CountryName
"1"         "Brazil"
"2"         "Germany"
"3"         "Canada"
"4"         "Norway"
"5"         "Czech Republic"
"6"         "Austria"
"7"         "Belgium"

客户表

"0" "CustomerId"    "INTEGER"   "1" "NULL"  "1"
"1" "FirstName" "VARCHAR(40)"   "1" "NULL"  "0"
"2" "LastName"  "VARCHAR(20)"   "1" "NULL"  "0"
"3" "Company"   "VARCHAR(80)"   "0" "NULL"  "0"
"4" "Address"   "VARCHAR(70)"   "0" "NULL"  "0"
"5" "City"  "VARCHAR(40)"   "0" "NULL"  "0"
"6" "State" "VARCHAR(40)"   "0" "NULL"  "0"
"7" "Country"   "VARCHAR(40)"   "0" "NULL"  "0"
"8" "PostalCode"    "VARCHAR(10)"   "0" "NULL"  "0"
"9" "Phone" "VARCHAR(24)"   "0" "NULL"  "0"
"10" "Fax"  "VARCHAR(24)"   "0" "NULL"  "0"
"11""Email" "VARCHAR(60)"   "1" "NULL"  "0"
"12""SupportRepId"  "INTEGER"   "0" "NULL"  "0"

1 个答案:

答案 0 :(得分:1)

RAND()函数生成一个随机数。您可以在ORDER BY中使用它来选择符合某些条件的随机行。

SELECT * FROM (
    (
    SELECT FirstName, LastName, CustomerId
    FROM Customer
    WHERE Country = 'Brazil'
    ORDER BY RANDOM()
    LIMIT 1
    ) 
UNION
    (
    SELECT FirstName, LastName, CustomerId
    FROM Customer
    WHERE Country = 'Germany'
    ORDER BY RANDOM()
    LIMIT 1
    ) 
UNION
    (
    SELECT FirstName, LastName, CustomerId
    FROM Customer
    WHERE Country = 'Canada'
    ORDER BY RANDOM()
    LIMIT 1
    )
)