Larry Brister
asked on
MS SQL that is more efficient than mine?
Is there a more efficient way to get the total rows on each returned line than what I am doing in my select?
THIS
Returns this
I am aware of the COUNT(*) OVER() as Total option but that seems to be excluded from the login when a select is done with a SELECT TOP (n)
Example...
The following SQL returns 100 rows of data
But SHOWS 1,754,123 as the total.
THIS
DECLARE @SalesSiteID INT = 56399;
WITH cte
AS ( SELECT n.NotificationID ,
n.NotificationText ,
n.DateAdded
FROM ewNotifications n
INNER JOIN ewNotificationsToSalesSites nss ON nss.NotificationID = n.NotificationID
WHERE n.IsGlobal = 1
AND n.DateExpired > GETDATE()
AND nss.SalesSiteID = @SalesSiteID
AND nss.IsRead = 0
GROUP BY n.NotificationID ,
n.NotificationText ,
n.DateAdded )
SELECT A.BadgeCount ,
cte.NotificationID ,
cte.NotificationText ,
cte.DateAdded
FROM cte
OUTER APPLY ( SELECT COUNT(*) BadgeCount
FROM cte ) A;
Returns this
I am aware of the COUNT(*) OVER() as Total option but that seems to be excluded from the login when a select is done with a SELECT TOP (n)
Example...
The following SQL returns 100 rows of data
But SHOWS 1,754,123 as the total.
SELECT TOP 100 i.IndividualID ,
COUNT(*) OVER () AS [Total_Rows]
FROM Individuals i
JOIN dbo.ewSalesSitesToIndividuals s ON i.IndividualID = s.IndividualID
JOIN SalesSites ss ON s.SalesSiteID = ss.SalesSiteID
WHERE ss.BusinessID = 2;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks
ASKER
I see that.
I am just noting that when you select TOP 2 in the second select
It returns two records but displays 3 total records on each row
I can see where that would be helpful as in
Add the row_number() and you could actually display something like the following when using TOP 100
Row 3 of 10,000 records. There are 100 Records in this table