Question

I'm newbie on tsql and stuck on this problem. Can anyone help this prb? I have a table like below; (use SQL 2008 Express Edt.)

ID    COL1    COL2
1      7      2
2      7      3
3      7      4
4      7      5
5      9      2
6      9      3
7      9      4
8      9      5
9      11     2
10     11     3
11     11     4
12     11     5

how to use select query to fetch between 7/3 and 11/2 (both columns and first/last rows included)

Was it helpful?

Solution

SQL Fiddle

MS SQL Server 2008 Schema Setup:

create table YourTable
(
  ID int,
  COL1 int,
  COL2 int
)

insert into YourTable values
(1   ,7     ,2),
(2   ,7     ,3),
(3   ,7     ,4),
(4   ,7     ,5),
(5   ,9     ,2),
(6   ,9     ,3),
(7   ,9     ,4),
(8   ,9     ,5),
(9   ,11    ,2),
(10  ,11    ,3),
(11  ,11    ,4),
(12  ,11    ,5)

Query 1:

select *
from YourTable
where (COL1 > 7 and COL1 < 11) or
      (COL1 = 7 and COL2 >= 3) or
      (COL1 = 11 and COL2 <= 2)

Results:

| ID | COL1 | COL2 |
--------------------
|  2 |    7 |    3 |
|  3 |    7 |    4 |
|  4 |    7 |    5 |
|  5 |    9 |    2 |
|  6 |    9 |    3 |
|  7 |    9 |    4 |
|  8 |    9 |    5 |
|  9 |   11 |    2 |
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top