I am new to SQL, so I need your help on a query. Basically I have a Database of ZipCodes and I want to get 3 items before the selected ZipCode and 3 items after. The Query that I came up with is pretty bad…
WITH numberedlogtable AS
(
SELECT *
FROM dbo.US
)
SELECT *
FROM numberedlogtable
WHERE ZipCode IN (SELECT ZipCode+i
FROM numberedlogtable
CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
WHERE ZipCode='91803')
I picked up a sample Query from somewhere and successfully converted it for my use. The only problem is that this Query returns current item and the next item. Instead, it should returns previous 3 items, current item, and next three items.
Using a common table expression (the
WITHpart) producing a numbered sequence:Normally in SQL there is no such concept as the previous or next items in a match. Actually, unless an order by clause is specified the rows are returned in any order that the sql engine find suitable. To make a query like this, an order has to be applied and index numbers generated. That’s done in NumberedZipCodes. The second part is just a query to get the data out of it.
To have the query run efficiently, make sure that there is an index on the
ZipCodecolumn.