Select data from a table based on the values in a column

98 views Asked by At

I need a query to select records in a table based on the column data.

My table is like this

ID col1 col2
1.  A.  Bsp

2.  B.  Ees.  

3.  Ç.  Eee 

4   D   Esp

5.  E.  Apt

6.  F.  Dpt

7.  G.  Bsp

8.  H.  Ees.  

9.  I.  Eee 

10   J   Esp

11.  K.  Apt

I need a query to select the records after 'bsp' till 'esp'.

Like this,

ID col1 col2

2.  B.  Ees.  

3.  Ç.  Eee 

4   D   Esp

8.  H.  Ees.  

9.  I.  Eee 

10   J   Esp
3

There are 3 answers

0
John Lichtenstein On

Please consider a function that looks at col1 and col2 and returns a 1 or True to keep and 0 or False otherwise. Use that function create a column and the column to query the dataframe.

def toKeep(a, b):
   if a == "B." and b == "Ees.":
        return 1
   elif a == "Ç." and b == "Eee":
        return 1
   else
        return 0

myTable["toKeep"] = [toKeep(a, b) for (a, b) \
    in zip(myTable["col1"], myTable["col2"])]

whatIwant = myTable.query("toKeep == 1")
0
User12345 On

Given the limited information provided, here is the solution based on sql server:

DECLARE @id_bsp INT;
DECLARE @id_esp INT;

SELECT @id_bsp = ID FROM YourTable WHERE col2 = 'Bsp';
SELECT @id_esp = ID FROM YourTable WHERE col2 = 'Esp';
 
SELECT ID, col1, col2
FROM YourTable
WHERE ID > @id_bsp AND ID <= @id_esp;

Here is sample fiddle link

0
DRapp On

you are dealing with a very simple WHERE clause... nothing fancy, no functions, just a WHERE clause.

select
      yt.*
   from
      YourTable yt
   where
          yt.col2 > 'bsp'
      AND yt.col2 <= 'esp'

That is the basic premise. Now if you are trying to call from some local program such as web or desktop app, build whatever command you have and parameterize the query so you are not hard-coding the 'bsp' and 'esp' values, but instead the "value of" whatever first and second parameter such as

select
      yt.*
   from
      YourTable yt
   where
          yt.col2 > @parmLowValue
      AND yt.col2 <= @parmHiValue

SQL-Server uses "@" to identify a parameter which you would prepare in your call to the database. Different sql databases may use different character to denote a parameter vs a fixed hard-coded value as in the first example.