views:

73

answers:

2

I have a simple query that runs in SQL 2008 and uses a custom CLR aggregate function, dbo.string_concat which aggregates a collection of strings.

I require the comments ordered sequentially hence the ORDER BY requirement.

The query I have has an awful TOP statement in it to allow ORDER BY to work for the aggregate function otherwise the comments will be in no particular order when they are concatenated by the function.

Here's the current query:

SELECT ID, dbo.string_concat(Comment) 
FROM (
    SELECT TOP 10000000000000 ID, Comment, CommentDate 
    FROM Comments 
    ORDER BY ID, CommentDate DESC
     ) x
GROUP BY ID

Is there a more elegant way to rewrite this statement?

+1  A: 

So... what you want is comments concatenated in order of ID then CommentDate of the most recent comment?

Couldn't you just do

SELECT ID, dbo.string_concat(Comment)
FROM Comments
GROUP BY ID
ORDER BY ID, MAX(CommentDate) DESC

Edit: Misunderstood your objective. Best I can come up with is that you could clean up your query a fair bit by making it SELECT TOP 100 PERCENT, it's still using a top but at least it gets around having an arbitrary number as the limit.

Tim Schneider
I don't think this will work, because ORDER BY is the last thing that happens when the query is executed. The way I understand it is that he needs things ordered before he groups them.
womp
Yes I need the order to occur before the group by so that the aggregate data is ordered correctly. In essence the concat function will output a time ordered list of comments as one big varchar(max).
Jafin
Ah, my bad, I misunderstood what you were trying to achieve.
Tim Schneider
Top 100 PERCENT is indeed an improvement.
Jafin
+1  A: 

Since you're using sql server 2008, you can use a Common Table Expression:

WITH cte_ordered (ID, Comment, CommentDate)
AS
(
    SELECT ID, Comment, CommentDate 
    FROM Comments 
    ORDER BY ID, CommentDate DESC
)
SELECT ID, dbo.string_concat(Comment) 
FROM cte_ordered
GROUP BY ID
womp
Nice one, but this still gives a Msg 1033, Level 15, State 1, Line 6The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.
Jafin
Gah, weak. You might need to go with a temporary table :/
womp