I want a more elegant way to select the top category in the table below by LastUpdatedDateTime descending. Basically I only want to see the latest single row for each Category by CategoryID.
I can get that by doing the following…
SELECT Category,
MAX(LastUpdateDateTime) as LastUpdateDateTime
INTO #t
FROM Settings
WHERE CatalogID = 123
GROUP BY Category
ORDER BY Category
SELECT s.*
FROM Settings s
INNER JOIN #t t
ON s.Category = t.Category
AND s.LastUpdateDateTime = t.LastUpdateDateTime
–> Settings table
CREATE TABLE [dbo].[Settings](
[ID] [int] IDENTITY(1,1) NOT NULL,
[CatalogID] [int] NOT NULL,
[Category] [varchar](50) NOT NULL,
[Facings] [bit] NOT NULL,
[Quantity] [bit] NOT NULL,
[LastUpdateDateTime] [datetime] NOT NULL,
CONSTRAINT [PK_Settings_1] PRIMARY KEY CLUSTERED
(
[ID] ASC,
[CatalogID] ASC,
[Category] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
This is pretty simple, just looking for someone to point me in the right direction to do this a little more efficiently. What I have WORKS. I want to refactor please.
Thanks for looking.
-B
How about a sub-query:
or even use CTE: