Mam to zapytanie (używam SQL Server 2019) i działa dobrze (łącząc daty i uwagi w jedną kolumnę). Jednak wynik, którego szukam, jest posiadanie najnowszej daty. Wpisz opis obrazu tutaj

Jak mogę to osiągnąć z tego zapytania?

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

Próbowałem zamówienia, ale nie pracuje tutaj, to mój stół:

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 
0
peka 21 marzec 2020, 05:51

1 odpowiedź

Najlepsza odpowiedź

Użyj 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;
2
Tim Biegeleisen 21 marzec 2020, 03:53