T-SQL SELECT按LastUpdateDateTime排序

时间:2012-09-26 18:03:50

标签: sql sql-server tsql

我希望以更优雅的方式通过LastUpdatedDateTime降序选择下表中的顶级类别。基本上我只想按类别ID查看每个类别的最新单行。

我可以通过以下方式得到它......

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

1 个答案:

答案 0 :(得分: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