简体   繁体   English

SQL:尝试为每个类别选择1个随机行

[英]SQL: Trying to select 1 random row for each category

I have a table which looks like this: 我有一个看起来像这样的表:

ID       Section        AlbumName        ImageName

1        Section1       Album1           Image1
2        Section1       Album1           Image2
3        Section1       Album2           Image3
4        Section2       Album3           Image4
5        Section3       Album4           Image5

What I'm trying to do is to get 1 random image from each section, I know at the moment I only have multiple images in Album1, this is just for testing. 我想要做的是从每个部分获得1个随机图像,我知道目前我在Album1中只有多个图像,这仅用于测试。

The SQL that I'm using is 我正在使用的SQL是

Select Distinct g.albumName,
(select top 1 gl.imageName 
from Gallery gl
where gl.Section = g.Section
and gl.AlbumName = g.AlbumName
order by newid()
) as imageName
from Gallery g

But this is not always giving me the results that I expect. 但这并不总是能给我我期望的结果。 Some times it will return 1 imageName for Album1 and other times it will return both imageNames. 有时它会为Album1返回1个imageName,有时会返回两个imageNames。

If I run the subquery by itself and substitute g.section with section1 and g.AlbumName with Album1 then only 1 result is returned, so i know it has something to do with the way i'm using the where conditions but I'm just not sure whats wrong. 如果我自己运行子查询并用section1替换g.section而用Album1替换g.AlbumName然后只返回1个结果,所以我知道它与我使用where条件的方式有关但我只是不确定什么是错的。

Can anybody suggest why this would be happening and how I can modify the query to get what I need? 任何人都可以建议为什么会发生这种情况以及如何修改查询以获得我需要的内容?

This method uses Common Table Expression and Windowing Function . 此方法使用Common Table ExpressionWindowing Function

WITH records 
AS
(
    SELECT  ID, [Section], AlbumName, ImageName,
            ROW_NUMBER() OVER (PARTITION BY [Section] ORDER BY NEWID()) rn
    FROM    TableName
)
SELECT  ID, [Section], AlbumName, ImageName
FROM    records
WHERE   rn = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM