开发者

How do I do a group by with a random aggregation function in SQL Server?

I have the following SQL:

select Username, 
    COUNT(DISTINCT Message) as "Count", 
    AVG(WordCount) as "Average",
    RAND(Message) //Essentially what I want to do 
from Messages
group by Username
order by "Count" desc

My two aggregation functions as columns are Count and Average, which are obvious. What I want to do is to also return a random row from each grouping from the 'Message' column.

I've written this query in Linq2SQL, however it doesn't support random numbers.

I think I need to create a custom aggregation function but they seem pretty over-the-top, and I want to know if there's an easier way before I try that. I'd try a CLR aggregation function, but then the database wouldn't be as easily portable between instances due to their dll nature.

I also know that using per-row random numbers in SQL is a bit verbose as well, but I can't find a way to use them in my group by query.

I've seen Marc Gravell's idea for random rows here: Random row from Linq to Sql, however his solution 开发者_JS百科pulls in every row which I don't want to do; only the grouping (which is orders of magnitude smaller.)


select Username, 
    COUNT(DISTINCT m.Message) as "Count", 
    AVG(m.WordCount) as "Average",
    FOO.Message
from
    Messages m
    cross apply
    (select TOP 1 Message, Username
       from Messages m2 
       WHERE m2.Username = m.Username
       order by newid()
    ) FOO
group by m.Username, FOO.Message
order by "Count" desc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜