I have a table with a column period. the value in this column will be like this, 201101, 201102, 201103,etc, 201112, 201201 etc If i give a number n and any period p, then it has to retrieve a period = p -开发者_开发百科 n. That means it has to go n period before. Please help me how to do this. Im using SQL Server 2008. Period column is integer type.
If I understand what you need, try this:
SELECT TOP 1 * FROM
(
SELECT TOP n * FROM your_table
WHERE period < p
ORDER BY period DESC) as tb
ORDER BY tb.period
My idea is first to take n periods backward (with subquery) and then take (with main query) the last record from subquery.
If you want a period (not only one record) you could use:
SELECT TOP n * FROM your_table
WHERE period < p
ORDER BY period DESC
If I'm understanding correctly, it looks like you'll need a between statement.
SELECT period from table where period between n and p
N and P are integer numbers in this case.
For further information about SQL, check out http://w3schools.com/sql/default.asp
you can try this ...
select * from your_table
where period = convert(varchar(6),dateadd(m,addnumber,convert(datetime,convert(varchar(6),startperiod)+'01')),112)
addnumer = month to add (positiv) or remove (negativ)
startperiod = start period
i think this is a better solution because if a period is actualy not in your table, then you would not get wrong results!
精彩评论