简体   繁体   中英

What is the difference between these two similar SQL ARRAY_TO_STRING statements?

I am sniffing out an error in my SQL query that revolves around the ARRAY_AGG function. Below are the following two lines of SQL.

The below line is the correct and complete SQL version that I ultimately want to have. This behavior is the behavior that results in a correct query.

ARRAY_TO_STRING((ARRAY_AGG(R.version ORDER BY R.released_on DESC))[1:10], ', ')

and this line here I thought would be equivalent but when I execute this line of SQL I receive ERROR: more than one row returned by a subquery used as an expression

ARRAY_TO_STRING(ARRAY_AGG((SELECT  "releases"."version" FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10)), ',')

I am arriving at this line of SQL through arel and is proving to be a little challenging but is it possible that the two lines could be equivalent? The first line is slicing an array to retrieve 10 items while the second is essentially doing the same thing albeit in rows. Could this be tweaked or will this need to be rewritten?

I haven't used ruby but it looks like the nesting in different between the two lines. Your ARRAY_AGG is getting two different sets of data.
First:

ARRAY_AGG(R.version ORDER BY R.released_on DESC)

Second:

ARRAY_AGG((SELECT  "releases"."version" FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10))

Looking there I think on your second statement is wrong, from what I see online it looks like ARRAY_AGG should be use as a column function not on a table set. Below are some links that I was looking at but I wan't sure which is correct as ARRAY_AGG looks to be a sql function and i'm not sure what flavor you are using...

https://msdn.microsoft.com/en-us/library/azure/mt763803.aspx
https://www.postgresql.org/docs/8.4/static/functions-aggregate.html

With that I think it should look like:

(SELECT  ARRAY_AGG("releases"."version") FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10)

Just a guess..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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