2012-09-26 46 views
0

我想要一個更優雅的方式,通過LastUpdatedDateTime降序選擇下表中的頂級類別。基本上我只想查看CategoryID的每個Category的最新單行。T-SQL SELECT頂部按LastUpdateDateTime分類

我可以通過執行以下操作...

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

怎麼樣一個子查詢:

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 
+0

我認爲ROW_NUMBER()的解決方案是更好的,在可能的情況下,搭配LastUpdateDateTime。另外,如果你使用*這樣的話,你會在結果中得到第一列(我意識到這可能只是爲了保持簡單和緊湊)。 – GilM

+0

@GilM我使用了'select *',因爲這是OP的內容,但通常我會在'SELECT'中指定每一列的需要。 :) – Taryn

+0

@bluefeet,第一個建議很好! Common Table Expressions的建議引起了我的興趣,但它只返回了一行。任何想法爲什麼?我有5個不同的行,我期望從我的數據集。 – brianhevans