Search code examples
sql-servert-sqlstring-aggregation

How to order by with string_agg


I have this query (I am using SQL Server 2019) and is working fine (combining Dates and Notes into one column). However, the result I am looking for is to have the latest date show up first. enter image description here

How can I achieve that from this query?

SELECT ID,            

​(SELECT string_agg(​concat(Date, ': ', Notes), CHAR(13) + CHAR(10) + CHAR(13) + CHAR (10)) as Expr1​

    FROM(SELECT DISTINCT nd.Notes, nd.Date
    FROM dbo.ReleaseTrackerNotes AS nd 
    INNER JOIN dbo.ReleaseTracker AS ac4 ON ac4.ID = nd.ReleaseTrackerID
    WHERE (ac4.ID = ac.ID)) AS z_1) AS vNotes 

FROM dbo.ReleaseTracker AS ac

GROUP BY ID

I have tried the ORDER BY but is not working Here is my table:

CREATE TABLE [dbo].[ReleaseTrackerNotes](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ReleaseTrackerID] [int] NULL,
    [AOC_ModelID] [int] NULL,
    [Date] [date] NULL,
    [Notes] [nvarchar](800) NULL,
 CONSTRAINT [PK_ReleaseTrackerNotes] PRIMARY KEY CLUSTERED 
CREATE TABLE [dbo].[ReleaseTracker](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [AOC_ModelID] [int] NOT NULL,
    [MotherboardID] [int] NOT NULL,
    [StatusID] [int] NOT NULL,
    [TestCateoryID] [int] NULL,
    [TestTypeID] [int] NULL,
    [DateStarted] [date] NULL,
    [DateCompleted] [date] NULL,
    [LCS#/ORS#] [nvarchar](20) NULL,
    [ETCDate] [date] NULL,
    [CardsNeeded] [nvarchar](2) NULL,
 CONSTRAINT [PK_Compatibility] PRIMARY KEY CLUSTERED 

Solution

  • Use WITHIN GROUP (ORDER BY ...):

    SELECT
        ID,            
        STRING_AGG(​TRY_CONVERT(varchar, Date, 101) + ': ' + Notes +
                   CHAR(13) + CHAR(10) + CHAR(13), CHAR(10))
            WITHIN GROUP (ORDER BY Date DESC) AS Expr1​
    FROM
    (
        SELECT DISTINCT ac4.ID, nd.Notes, nd.Date
        FROM dbo.ReleaseTrackerNotes AS nd 
        INNER JOIN dbo.ReleaseTracker AS ac4
            ON ac4.ID = nd.ReleaseTrackerID
    ) AS vNotes
    GROUP BY ID;