Merging SQL query for results that are alike - c#

I have a system right now that stores products and tags that are associated with each product.
Example
Product: Microphone
Tags: Music, Electronics, Audio
There is a Tag table, Product Table, and TagProductMapping Table. The third table obviously maps the product to the tags for a one to many relation. When I query the Microphone product using a LEFT JOIN I get 3 records that are almost duplicate except the "TagName" column where obviously it has all 3 different tags. How can I merge this result? Its frustrating because if I try to query exactly 10 products, it will only limit to 10 results, which wouldnt really be 10 products.
Anyone have a good idea for this?
EDIT:
Here is the result on my query, notice how the only thing different between the 3 JobId's are the CategoryName, which are the tags.
Here are what my tables look like
-Tagmapping table:
-Tag Table
-"products table" (in this case, its my job table)
Here is my stored procedure:
ALTER PROCEDURE [dbo].[JobPostingSelectAll]
(
#StartRowIndex INT,
#PageSize INT,
#OrderBy VARCHAR(50),
#OrderByDirection VARCHAR(4),
#CurrentUserId INT,
#CategoryId INT
)
AS
SET NOCOUNT ON
SELECT
JobId,
Title,
Answers,
UserId,
UserName,
ProfileImageName,
CategoryId,
CategoryName,
Fees,
DESCRIPTION,
DateCreated,
UniqueTitle,
IsSecured
FROM (
SELECT J.JobId,
J.Title,
(SELECT COUNT(ja2.JobId) FROM JobApplication ja2 left join Deliverable d2 ON d2.DeliverableId = ja2.DeliverableId
WHERE ja2.JobId=j.JobId and (d2.PurchaseCount>0 OR d2.IsFrozen=0)) AS Answers,
J.UserId,
U.UserName,
U.ImageName as ProfileImageName,
J.CategoryId,
C.CategoryName,
J.Fees,
J.Description,
J.DateCreated,
J.UniqueTitle,
J.IsSecured,
ROW_NUMBER() OVER(
ORDER BY
CASE
WHEN #OrderByDirection = 'asc' AND #OrderBy = 'Answers'
THEN (SELECT COUNT(ja2.JobId) FROM JobApplication ja2 left join Deliverable d2 ON d2.DeliverableId = ja2.DeliverableId
WHERE ja2.JobId=j.JobId and (d2.PurchaseCount>0 OR d2.IsFrozen=0)) END ASC,
CASE
WHEN #OrderByDirection = 'asc' AND #OrderBy = 'Answers'
THEN J.DateCreated END DESC,
CASE
WHEN #OrderByDirection = 'asc' AND #OrderBy = 'Answers'
THEN J.Title END ASC,
CASE
WHEN #OrderByDirection = 'desc' AND #OrderBy = 'Answers'
THEN (SELECT COUNT(ja2.JobId) FROM JobApplication ja2 left join Deliverable d2 ON d2.DeliverableId = ja2.DeliverableId
WHERE ja2.JobId=j.JobId and (d2.PurchaseCount>0 OR d2.IsFrozen=0)) END DESC,
CASE
WHEN #OrderByDirection = 'desc' AND #OrderBy = 'Answers'
THEN J.DateCreated END DESC,
CASE
WHEN #OrderByDirection = 'desc' AND #OrderBy = 'Answers'
THEN J.Title END ASC,
CASE WHEN #OrderByDirection = 'asc' AND #OrderBy = 'Fees'
THEN J.Fees END ASC,
CASE WHEN #OrderByDirection = 'asc' AND #OrderBy = 'Fees'
THEN J.DateCreated END DESC,
CASE WHEN #OrderByDirection = 'desc' AND #OrderBy = 'Fees'
THEN J.Fees END DESC,
CASE WHEN #OrderByDirection = 'desc' AND #OrderBy = 'Fees'
THEN J.DateCreated END DESC,
CASE WHEN #OrderByDirection = 'asc' AND #OrderBy = 'DateCreated'
THEN J.DateCreated END ASC,
CASE WHEN #OrderByDirection = 'desc' AND #OrderBy = 'DateCreated'
THEN J.DateCreated END DESC
) AS RowIndex
FROM [JobPosting] J
LEFT JOIN TagMapping TM ON J.JobId = TM.QuestionId
LEFT JOIN Categories C ON TM.TagId = C.CategoryID
Left Join [User] U ON J.UserId = U.UserID
WHERE J.IsLocked = 0 AND j.IsDeleted = 0
AND (#CategoryId IS NULL OR J.CategoryId = #CategoryId)
) AS JobPostingList
WHERE RowIndex BETWEEN #StartRowIndex AND (#StartRowIndex + #PageSize) - 1
SELECT COUNT(J.JobID) AS TotalRecords
FROM JobPosting J
WHERE J.IsLocked = 0 AND J.IsDeleted = 0
AND (#CategoryId IS NULL OR J.CategoryId = #CategoryId)
-- select all filecount grouped by Type Of File for specific Job
SELECT J.JobId, F.MimeType, COUNT(F.FileId) AS FileCount
FROM
JobPosting J
Left Join Files F ON F.JobPostingId = J.JobId
WHERE J.IsLocked = 0 AND J.IsDeleted = 0
AND (#CategoryId IS NULL OR J.CategoryId = #CategoryId)
GROUP BY
F.MimeType,J.JobId
Having COUNT(F.FileId) > 0

The issue you're having occurs because your database structure normalizes tag data for each product (I've found this page to be a good reference).
When you SELECT from your Products table and JOIN over to your Tags table, it's crucial to remember that you're not getting a list of Products; rather, you're getting a listing of Product-Tag combinations.
If you want to get a list of the top 10 products along with their tag information, I'd suggest using a subquery:
select * from
(select top 10 * from ProductsTable) TopProducts
inner join Tagmapping on TopProducts.ProductID = Tagmapping.ProductID
inner join Tags on Tagmapping.TagID = Tags.TagID
Even though this solves your initial selection issue, this will still produce the kind of multiple listing you show above where only the tag information differs from row to row.
It's possible to format the output to have multiple tag entries (maybe separated by commas) as described here, but that's going to be something you want to do as a last step before you present the data to the user, either through SQL or whatever software layer you're using as a go-between.

I believe that if you are not interested in the tag name, you can select all columns except the tag name and use "select distinct" to show just the products without its tags. I can be wrong though =(

Related

Timeout expired. The timeout period elapsed prior to completion of the operation

I an a stored procedure which selects files with pagination criteria
In this problem, when run this stored procedure, get an exception
Timeout expired. The timeout period elapsed prior to completion of the operation
How to works again without above exception?
My researches and tries:
I compared same db on two database servers(prod and test). Test server can work and prod one can not.
I changed connecion string to add "connect timeout=30000" (5 mins)
I also added CommandTimeOut=30000 at file list method.
Additional information: Prod's db server and IIS server placed different server. I searced some articles and because of the slow connection or heavier traffic on db server. But I encountered this error at first time on today.
My stored procedure located below
ALTER PROCEDURE [dbo].[inwsDosyaListesiSirali]
#SiteId INT,
#KullaniciId int,
#SubeIp varchar(max),
#DepartmanId int,
#KategoriKod VARCHAR(200)= null,
#Baslik VARCHAR(100) = null,
#IlkTarih DATETIME=null,
#SonTarih DATETIME=null,
#Icerik varchar(max) = null,
#PageNumber INT=1,
#PageSize INT=10,
#SortColumn varchar(100)=null,
#SortOrder BIT=null
AS
BEGIN
DECLARE #KategoriKodListe TABLE(KategoriKod VARCHAR(20) primary key);
INSERT INTO #KategoriKodListe
SELECT Item FROM dbo.SplitString(#KategoriKod,',')
declare #SubeId int,
#DepartmanTurId int ,
#SubeKategoriKod varchar(100)
SELECT #DepartmanTurId=[DepartmanTurId] FROM [Departman]
where [SiteId]=#SiteId and [Id] = #DepartmanId
select #SubeId=ks.SubeId, #SubeKategoriKod = ksk.Kod from [dbo].[KurumsalSube] ks
inner join [dbo].[KurumsalSubeKategori] ksk on ks.KategoriId = ksk.KategoriId
where SiteId=#SiteId and SubeIp like '%'+#SubeIp+'%'
;With EMP AS (
SELECT
r.RaporId
,r.HistoryId
,r.Baslik
,r.DosyaAd
,r.RaporAktifTarih
,r.RaporGecerlilikTarih
,r.RaporTarih
,r.KategoriId
,h.KayitTarih
,r.ParentRaporId
,kat.Ad [KategoriAd]
,kat.Kod [KategoriKod]
,kat.Sira
,T.DosyaTurId
,T.Ad AS DosyaTurAd
--,T.Uzanti AS DosyaUzanti
,T.iconName
--,(ROW_NUMBER() OVER (PARTITION BY r.[KategoriId] ORDER BY r.[RaporTarih] desc)) AS number
,s.SistemDosyaId
,s.DosyaAdi as SistemDosyaAd
FROM Dosya r
INNER JOIN DosyaKategori kat ON kat.KategoriId=r.KategoriId
INNER JOIN DosyaHistory h ON h.Id=r.HistoryId
LEFT JOIN DosyaTur T ON T.DosyaTurId=r.DosyaTurId
LEFT JOIN DosyaIcerik di ON r.SistemDosyaId = di.SistemDosyaId
--Yetki kontrol kısmı
left join [dbo].[DosyaYetki] dy on r.DosyaYetkiId = dy.DosyaYetkiId
LEFT JOIN SistemDosyalari s ON s.SistemDosyaId=r.SistemDosyaId
WHERE kat.SiteId=#SiteId AND r.IsOnay=1
AND (isnull(#KategoriKod,'') = '' or exists(select 1 from #KategoriKodListe k where k.KategoriKod=kat.Kod) )
AND ((NULLIF(r.RaporGecerlilikTarih,'') IS NULL OR (r.RaporGecerlilikTarih >= GETDATE())))
AND ((NULLIF(r.RaporAktifTarih,'') IS NULL OR (r.RaporAktifTarih <= GETDATE())))
-- AND ((NULLIF(#Baslik,'') IS NULL OR (r.Baslik like '%'+#Baslik+'%' ) OR NULLIF(r.ParentRaporId,'') IS NOT NULL))
--AND ((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date, DATEADD(day,0,r.RaporTarih)))))
--AND ((NULLIF(#SonTarih,'') IS NULL OR (#SonTarih>=CONVERT(date, DATEADD(day,0,r.RaporTarih)))))
--AND ((NULLIF(#Icerik,'') IS NULL OR (di.Icerik like '%'+#Icerik+'%') OR NULLIF(r.ParentRaporId,'') IS NOT NULL))
--Yetki kontrol kısmı
and (
dy.DosyaYetkiId is null or
(
dy.SiteId=#SiteId and
(
r.DosyaYetkiId is null or r.[HerkeseGosterilsin]=1 or -- herkese açık demek oluyor
(#DepartmanTurId=1 and #SubeKategoriKod='INGENELMUDURLUK' ) or -- Kategori Kod : INGENELMUDURLUK ve yönetim departmanında ise tüm dosyaları görebilsin
(
(
-- Isnull(dys.SubeId,'')='' or
-- dys.SubeId=#SubeId
exists(select 1 from [dbo].[DosyaYetkiSube] dys where dys.SubeId=#SubeId )
or not exists(select 1 from [dbo].[DosyaYetkiSube] dys where dys.DosyaYetkiId=r.DosyaYetkiId )
)and
(
#DepartmanTurId=1 -- #DepartmanTurId=1 ise şubenin yönetici olarak o şubede ki tüm dosyaları görebilir
-- or Isnull(dyd.DepartmanId,'')=''
-- dyd.DepartmanId=#DepartmanId
or exists(select 1 from [dbo].[DosyaYetkiDepartman] dyd where dyd.DepartmanId = #DepartmanId)
or not exists(select 1 from [dbo].[DosyaYetkiDepartman] dyd where dyd.DosyaYetkiId = r.DosyaYetkiId )
)and
(
#DepartmanTurId=1 -- #DepartmanTurId=1 ise şubenin yönetici olarak o şubede ki tüm dosyaları görebilir
-- or Isnull(dyp.PersonelId,'')=''
-- dyp.PersonelId=#KullaniciId
or exists(select 1 from [dbo].[DosyaYetkiPersonel] dyp where dyp.PersonelId=#KullaniciId )
or not exists(select 1 from [dbo].[DosyaYetkiPersonel] dyp where dyp.DosyaYetkiId = r.DosyaYetkiId )
)
)
)
)
)
),
cte AS
(
SELECT CAST(ROW_NUMBER() OVER(order by
CASE WHEN (RTRIM(LTRIM(#SortColumn)) IS NULL)
THEN KayitTarih END DESC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=1)
THEN Baslik END ASC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=0)
THEN Baslik END DESC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=1)
THEN KayitTarih END ASC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=0)
THEN KayitTarih END DESC
) AS REAL) AS NUMBER, 1 AS Indent, Parent.* FROM EMP Parent WHERE Parent.ParentRaporId IS NULL
UNION ALL
SELECT c.NUMBER + (CAST(ROW_NUMBER() OVER(ORDER BY
CASE WHEN (RTRIM(LTRIM(#SortColumn)) IS NULL)
THEN child.KayitTarih END DESC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=1)
THEN child.Baslik END ASC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=0)
THEN child.Baslik END DESC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=1)
THEN child.KayitTarih END ASC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=0)
THEN child.KayitTarih END DESC
) AS REAL)/POWER(10, c.Indent) ) AS NUMBER, c.Indent + 1 AS Indent, child.* FROM EMP
child INNER JOIN cte c ON child.ParentRaporId= c.RaporId
),Count_CTE AS (
SELECT COUNT(*) AS [TotalCount]
FROM cte
WHERE (NULLIF(#Baslik,'') IS NULL OR (cte.Baslik like '%'+#Baslik+'%' ))
AND ((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date,
DATEADD(day,0,cte.RaporTarih)))))
AND ((NULLIF(#SonTarih,'') IS NULL OR (#SonTarih>=CONVERT(date,
DATEADD(day,0,cte.RaporTarih)))))
) SELECT * FROM cte, Count_CTE
WHERE (NULLIF(#Baslik,'') IS NULL OR (cte.Baslik like '%'+#Baslik+'%' ))
AND ((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date, DATEADD(day,0,cte.RaporTarih)))))
AND ((NULLIF(#SonTarih,'') IS NULL OR (#SonTarih>=CONVERT(date, DATEADD(day,0,cte.RaporTarih)))))
ORDER BY cte.NUMBER
OFFSET (#PageNumber-1)*#PageSize ROWS FETCH NEXT #PageSize ROWS ONLY
END
Add OPTION RECOMPILE and transform the non-SARGable where clauses. see http://sommarskog.se/dyn-search.html
eg
((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date, DATEADD(day,0,cte.RaporTarih)))))
should be
#IlkTarih is null or cast(#IlkTarih as date)<=cte.RaporTarih
I resolved this issue with adjust memory on SQL Server management studio because of low memory of db server.
If record is high, then query execution can take a long time.

How to make a schedule table query from SQL Server 2012?

I need help to make a schedule table for employee from my table the main problem is the row not start from first row on every column so the row keep continue, see picture below:
we can see that the next column is null on the first row and continue from the last row. this is my query and table relations, you can see it below.
SELECT (SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Tuesday')) AS Selasa,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Wednesday')) AS Rabu,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Thursday')) AS Kamis,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Friday')) AS Jumat,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Sabtu')) AS Saturday,
(SELECT PEGAWAI.NAMAPEGAWAI
WHERE (JADWAL.HARIKERJA = 'Monday')) AS Minggu FROM JADWAL INNER JOIN
JADWALPEGAWAI ON JADWAL.IDJADWAL = JADWALPEGAWAI.IDJADWAL INNER JOIN
PEGAWAI ON JADWALPEGAWAI.IDPEGAWAI = PEGAWAI.IDPEGAWAI WHERE (JADWAL.SHIFT = 'I')
What seems to be causing your query not to behave as you expect, is that you have no GROUP BY clause in your query, which means that you get one row of output for each for (in this case) each row of the JadwalPegawai table.
At a minimum, adding GROUP BY Pegawai.NamaPegawai after your WHERE … clause should fix this, but I think that we can do even better:
Select Min(iif(j.Harikerja = 'Tuesday', p.NamaPegawai, Null)) As Selasa,
Min(iif(j.Harikerja = 'Wednesday', p.NamaPegawai, Null)) As Rabu,
…
From Jadwal As j
Join JadwalPegawai As jp On j.IdJadwal = jp.IdJadwal
Join Pegawai As p On jp.IdPegawai = p.IdPegawai
Where j.Shift = 'I'
Group By p.NamaPegawai;
This should be logically equivalent, but doesn't use subqueries. Hope I didn't make any spelling errors, I'm not too good at bahasa Indonesia...

I want the last entries in my Microsoft SQL Server database but get duplication

My problem is that I want to start a database query which should give me the last (maxDate) entry of every Serial number.
I am working with a Microsoft SQL Server database.
The first picture shows all entries in the database:
After I have run the following code I get this output:
string aQuery = #" SELECT *
FROM (
SELECT SerialNumber, MAX(Date) as MaxDate
FROM eBox_Deploy
GROUP BY SerialNumber
) r
INNER JOIN eBox_Deploy t
ON t.SerialNumber = r.SerialNumber AND t.Date = r.MaxDate";
using (var db = new eBoxDataContext())
{
list.AddRange(db.ExecuteQuery<eBox_Deploy>(bQuery));
}
After picture:
Now my problem is that I have duplicates because they already exists in the database. Distinct doesn't work well because these all have different Id´s.
How can I get them away?
You could use windowed functions:
SELECT *
FROM (SELECT *,
rn = ROW_NUMBER() OVER(PARTITION BY [SerialNumber] ORDER BY [Date] DESC)
FROM eBox_Deploy) AS sub
WHERE rn = 1;
If your [Date] is not unique within SerialNumber group use RANK() to get ties.

Complicated SQL Server query

I am trying to write an SQL (Server) query which will return all events on a current day, and for all events where the column recurring= 1, I want it to return this event on the day it is being held and for the subsequent 52 weeks following the event.
My tables are structured as followed :
Event
{
event_id (PK)
title,
description,
event_start DATETIME,
event_end DATETIME,
group_id,
recurring
}
Users
{
UserID (PK)
Username
}
Groups
{
GroupID (PK)
GroupName
}
Membership
{
UserID (FK)
GroupID (FK)
}
The code I have thus far is as follows :
var db = Database.Open("mPlan");
string username = HttpContext.Current.Request.Cookies.Get("mpUsername").Value;
var listOfGroups = db.Query("SELECT GroupID FROM Membership WHERE UserID = (SELECT UserID from Users WHERE Username = #0 )", username);
foreach(var groupID in listOfGroups)
{
int newGroupID = groupID.GroupID;
var result = db.Query(
#"SELECT e.event_id, e.title, e.description, e.event_start, e.event_end, e.group_id, e.recurring
FROM event e
JOIN Membership m ON m.GroupID = e.group_id
WHERE e.recurring = 0
AND m.GroupID = #0
AND e.event_start >= #1
AND e.event_end <= #2
UNION ALL
SELECT e.event_id, e.title, e.description, DATEADD(week, w.weeks, e.event_start), DATEADD(week, w.weeks, e.event_end), e.group_id, e.recurring
FROM event e
JOIN Membership m ON m.GroupID = e.group_id
CROSS JOIN
( SELECT row_number() OVER (ORDER BY Object_ID) AS weeks
FROM SYS.OBJECTS
) AS w
WHERE e.recurring = 1
AND m.GroupID = #3
AND DATEADD(WEEK, w.Weeks, e.event_start) >= #4
AND DATEADD(WEEK, w.Weeks, e.event_end) <= #5", newGroupID, start, end, newGroupID, start, end
);
This results in when one queries for the date of the event stored in the database, this event and 52 weeks of events are returned. When one queries for the event the week after this one, nothing is returned.
The simplest solution would be to alter the following 2 lines
AND e.event_start >= #4
AND e.event_end <= #5"
to
AND DATEADD(WEEK, w.Weeks, e.event_start) >= #4
AND DATEADD(WEEK, w.Weeks, e.event_end) <= #5"
However, I'd advise putting all this SQL into a stored procedure, SQL-Server will cache the execution plans and it will result in (slightly) better performance.
CREATE PROCEDURE dbo.GetEvents #UserName VARCHAR(50), #StartDate DATETIME, #EndDate DATETIME
AS
BEGIN
-- DEFINE A CTE TO GET ALL GROUPS ASSOCIATED WITH THE CURRENT USER
;WITH Groups AS
( SELECT GroupID
FROM Membership m
INNER JOIN Users u
ON m.UserID = u.UserID
WHERE Username = #UserName
GROUP BY GroupID
),
-- DEFINE A CTE TO GET ALL EVENTS FOR THE GROUPS DEFINED ABOVE
AllEvents AS
( SELECT e.*
FROM event e
INNER JOIN Groups m
ON m.GroupID = e.group_id
UNION ALL
SELECT e.event_id, e.title, e.description, DATEADD(WEEK, w.weeks, e.event_start), DATEADD(WEEK, w.weeks, e.event_end), e.group_id, e.recurring
FROM event e
INNER JOIN Groups m
ON m.GroupID = e.group_id
CROSS JOIN
( SELECT ROW_NUMBER() OVER (ORDER BY Object_ID) AS weeks
FROM SYS.OBJECTS
) AS w
WHERE e.recurring = 1
)
-- GET ALL EVENTS WHERE THE EVENTS FALL IN THE PERIOD DEFINED
SELECT *
FROM AllEvents
WHERE Event_Start >= #StartDate
AND Event_End <= #EndDate
END
Then you can call this with
var result = db.Query("EXEC dbo.GetEvents #0, #1, #2", username, start, end);
This elimates the need to iterate over groups in your code behind. If this is actually a requirement then you could modify the stored procedure to take #GroupID as a parameter, and change the select statements/where clauses as necessary.
I have assumed knowledge of Common Table Expressions. They are not required to make the query work, they just make things slightly more legible in my opinion. I can rewrite this without them if required.
I would check my parameters one at a time against some trivial SQL, just to rule them out as possible culprits. Something like this:
var result = db.Query("select r=cast(#0 as varchar(80))",username);
var result = db.Query("select r=cast(#0 as int)",newGroupID);
var result = db.Query("select r=cast(#0 as datetime)",start);
var result = db.Query("select r=cast(#0 as datetime)",end);

SQL + ASP.Net Efficient paging

My method of paging is inefficient as it calls the same query twice therefore doubling the query time. I currently call the 1 query that joins about 5 tables together with XML search querys to allow for passing List from ASP.net.. then I need to call exactly the same query except with a Count(row) to get the amount of records
For Example (I have removed bits to make it easier to read)
Main Query:
WITH Entries AS (
select row_number() over (order by DateReady desc)
as rownumber, Columns...,
from quote
join geolookup as Pickup on pickup.geoid = quote.pickupAddress
where
quote.Active=1
and //More
)
select * from entries
where Rownumber between (#pageindex - 1) * #pagesize + 1 and #pageIndex * #pageSize
end
Count Query:
select count(rowID)
from quote
join geolookup as Pickup on pickup.geoid = quote.pickupAddress
where
quote.Active=1
and //More
)
You could select the results of your big query into a temp table, then you could query this table for the row number and pull out the rows you need.
To do this, add (after your select statement and before the from)
INTO #tmpTable
Then reference your table as #tmpTable
select row_number() over (order by DateReady desc)
as rownumber, Columns...,
into #tmpTable
from quote
join geolookup as Pickup on pickup.geoid = quote.pickupAddress
where
quote.Active=1
and //More
)
SELECT #Count = COUNT(*) FROM #tmpTable
select * from #tmpTable
where Rownumber between (#pageindex - 1) * #pagesize + 1 and #pageIndex * #pageSize
You can set an output parameter which will hold the number of rows from the first query.
You could do something like
WITH Entries AS (
select row_number() over (order by DateReady desc)
as rownumber, Columns...,
from quote
join geolookup as Pickup on pickup.geoid = quote.pickupAddress
where
quote.Active=1
and //More
)
select #rowcount = max(rownumber) from entries
select * from entries
where Rownumber between (#pageindex - 1) * #pagesize + 1 and #pageIndex * #pageSize
Hope this helps

Categories

Resources