I create a query in linq which returns a table of most active salesmen in my shop:
ProjectDB3Context db = new ProjectDB3Context();
db.Database.Log = message => Trace.WriteLine(message);
var result = db.tblUsers.Join(db.tblSales,
u => u.ID,
sl => sl.tblUserId,
(u, sl) => new { u, sl })
.Select(o => new
{
UserId = o.u.ID,
Login = o.u.UserLogin,
FullName = o.u.Name + " " + o.u.Surname,
ItemsToSell = db.tblSales.Where(x => x.tblUserId == o.u.ID).Count()
})
.Distinct()
.OrderByDescending(x => x.ItemsToSell)
.ToList();
The henerated SQL query looks like:
SELECT
[Distinct1].[C1] AS [C1],
[Distinct1].[ID] AS [ID],
[Distinct1].[UserLogin] AS [UserLogin],
[Distinct1].[C2] AS [C2],
[Distinct1].[C3] AS [C3]
FROM ( SELECT DISTINCT
[Project1].[ID] AS [ID],
[Project1].[UserLogin] AS [UserLogin],
1 AS [C1],
[Project1].[Name] + N' ' + [Project1].[Surname] AS [C2],
[Project1].[C1] AS [C3]
FROM ( SELECT
[Extent1].[ID] AS [ID],
[Extent1].[UserLogin] AS [UserLogin],
[Extent1].[Name] AS [Name],
[Extent1].[Surname] AS [Surname],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[tblSale] AS [Extent3]
WHERE [Extent3].[tblUserId] = [Extent1].[ID]) AS [C1]
FROM [dbo].[tblUser] AS [Extent1]
INNER JOIN [dbo].[tblSale] AS [Extent2] ON [Extent1].[ID] = [Extent2].[tblUserId]
) AS [Project1]
) AS [Distinct1]
ORDER BY [Distinct1].[C3] DESC
Statistics:
SQL Server Execution Times:
CPU time = 359 ms, elapsed time = 529 ms.
I want to optimize the generated SQL query and insert optimized query into a stored procedure. SQL Server Management Studio gives me a tip to create a nonclustered index (tblUserId) on tblSale (you can see this tip in image that I included).
When I create it using command:
CREATE NONCLUSTERED INDEX IX_ProductVendor_tblUserId
ON tblSale (tblUserId);
and then run the SQL query in SQL Server Management Studio I get:
SQL Server Execution Times:
CPU time = 328 ms, elapsed time = 631 ms.
So it takes much longer after I used index to optimize my SQL query.
Can anybody help me with optimize this query in SQL Server using indexes?
tblUsers) and then not using the second table record in the projection.