Created
January 23, 2012 16:34
-
-
Save jdaigle/1664126 to your computer and use it in GitHub Desktop.
one-to-many efficient query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE [Foo] ( | |
[FooId] [int] NOT NULL, | |
[SomeDateTime] [datetime2](7) NOT NULL, | |
-- ... OTHER COLUMNS | |
[Version] rowversion NOT NULL, | |
CONSTRAINT [PK_Foo] PRIMARY KEY CLUSTERED ([FooId]) | |
) | |
CREATE TABLE [FooBar] ( | |
[FooBarId] [int] NOT NULL, | |
[FooId] [int] NOT NULL, | |
[BarId] [int] NOT NULL | |
CONSTRAINT [PK_FooBar] PRIMARY KEY CLUSTERED ([FooBarId]) | |
) | |
CREATE NONCLUSTERED INDEX [IX_SomeDateTime] ON [Foo] ([SomeDateTime] DESC) INCLUDE ([version]) | |
CREATE UNIQUE NONCLUSTERED INDEX [UX_FooId_BarId] ON [FooBar] ([FooId],[BarId]) | |
;WITH selectFoos AS | |
( | |
SELECT | |
Foo.FooId, | |
Foo.[Version], | |
ROW_NUMBER() OVER(ORDER BY Foo.[DateTime] DESC) AS RowNumber | |
FROM Foo | |
LEFT OUTER JOIN FooBar ON FooBar.FooId = Foo.FooId | |
WHERE Foo.[DateTime] >= '2012-01-02' AND Foo.[DateTime] <= '2012-01-03' | |
AND (FooBar.BarId IS NULL OR FooBar.BarId = 1 OR FooBar.BarId = 2) | |
and Foo.FooId = FooBar.FooId | |
GROUP BY Foo.FooId, Foo.[Datetime], Foo.[Version] | |
) | |
SELECT | |
FooId | |
,[Version] | |
FROM selectFoos | |
WHERE RowNumber BETWEEN 50 AND 100 | |
OPTION (RECOMPILE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment