0

我想要一种更优雅的方式来按 LastUpdatedDateTime 降序选择下表中的顶级类别。基本上我只想按 CategoryID 查看每个 Category 的最新单行。

我可以通过执行以下操作来实现...

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

--> 设置表

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]

这很简单,只是找人为我指出正确的方向,以便更有效地做到这一点。我有什么工作。我想重构一下。

感谢您的关注。

-B

4

1 回答 1

4

子查询怎么样:

select s1.*
from settings s1
inner join
(
  select category, max(LastUpdateDateTime) as LastUpdateDateTime
  from settings
  where catalogid = 123
  group by category
) s2
  on s1.category = s2.category
  and s1.LastUpdateDateTime = s2.LastUpdateDateTime

甚至使用 CTE:

;with cte as
(
  select *, 
    row_number() over(partition by catalogid 
                      order by LastUpdateDateTime desc) rn
  from settings
  where catalogid = 123
)
select *
from cte
where rn = 1
于 2012-09-26T18:08:20.363 回答