How to request a random column in SQL?

2019-06-24 15:04发布

How can I request a random column (or as close to truly random as is possible) in pure SQL?

I want to select any one column randomly from a table.

I have searched lot regarding this on google.

标签: sql random
4条回答
一纸荒年 Trace。
2楼-- · 2019-06-24 15:24

You can select a random record, but all columns must be referenced by name and not even position.

The only way you can force this is:

  1. Get list all column names
  2. Randomly select one column name
  3. Write the query using the selected column name

Simply there is no way to do it with pie SQL.

查看更多
SAY GOODBYE
3楼-- · 2019-06-24 15:34

In Microsoft SQL, you can achieve this by ordering columns by randomized number (NEWID):

SELECT TOP 1 c.column_name 
FROM   information_schema.columns c 
WHERE  table_name = 'your_table_name' 
ORDER  BY NEWID();
查看更多
Bombasti
4楼-- · 2019-06-24 15:35
USE [AdventureWorksDW2012]
GO

DECLARE @SQL VARCHAR(MAX)

SELECT  [name]
FROM    sys.columns C WHERE C.object_id = OBJECT_ID('DimProduct')
AND     C.column_id = (
SELECT  ((ABS(CHECKSUM(NEWID()))% COUNT(*)) + 1)
FROM    sys.columns C 
WHERE   C.object_id = OBJECT_ID('DimProduct'))

This may help you, It is done with SQL Server. Here you are randomly selecting a column of table [DimProduct]

Result1:

enter image description here

Result2:

enter image description here

查看更多
甜甜的少女心
5楼-- · 2019-06-24 15:36

Dependent on your DBMS the catalogue looks a bit different. For mysql you could get a random column like:

select column_name 
from information_schema.columns 
where table_schema = ? 
  and table_name = ? 
order by rand() limit 1;

and then incorporate that into your query. Other vendors may have a slightly different look of the catalogue, but the idea will be the same.

Why do you want to retrieve a random column?

查看更多
登录 后发表回答