sql group where clause

52 Views Asked by At

I have a table like this:

| grpType | grpId  | paramId |   val |
|---------|--------|:-------:|------:|
| 0       | 81452  |   123   | 1,293 |
| 0       | 81452  |   127   |    46 |
| 2       | 19873  |   282   |     3 |
| 2       | 19873  |   283   | -10,3 |
| 3       | 81455  |   123   | 1,144 |
| 3       | 100379 |   178   |    40 |
| 3       | 100379 |   188   |   269 |
| 3       | 100379 |   189   |   298 |
| 3       | 100379 |   190   |   267 |
| 3       | 100379 |   191   |   278 |
| 1       | 256    |   188   |   419 |
| 1       | 256    |   189   |   433 |
| 1       | 256    |   190   |   434 |
| 1       | 256    |   191   |   429 |

I want to get data from this table with conditions such as "paramId = 123 and val> = 1.2", "paramId=188 and val<=269", "paramId=189 and val>=298".

Here, since the conditions of "paramId = 188 and val <=269" and "paramId = 189 and val >298" have the same "grpId" in the table, both conditions specified for the "Val" column should provide. In the table above, There are 2 groups that meet the "paramId = 188, paramId = 189" condititon. I have to get the group that provides the requirement of "paramId = 188 and val <=269" and "paramId = 189 and val >298".(so the group of 100379 id)

However, the rows that provide the third condition (paramId = 123 and val >= 1.2) should be added to the data. In the table above, there are two "paramId = 123" row. I have to get the row that provides the requirement of "val >= 1.2".

The "grpType" column is not an important column. You can ignore. I just need a distinct "grpID" list.

How should the query be I will write?

2

There are 2 best solutions below

5
Roshan Nuvvula On

You can write combination of these conditions use OR in where condition.


Select *
from <TableName>
where ((paramId = 123 and Val >= 1.2) or (paramid=188 and Val <= 269) or (paramid=189 and Val <= 298))

0
Abdulkadir Avcı On

It's like a query will work. If I use intersect, I can't get the rows itself. I can only get common data. It's enough for me now. The number of rows in this table is over 3 million and is constantly increasing. I'm a little worried about performance. I will continue the research.

(select grpId from tableX where paramId=51 and val>=600
intersect
select grpId from tableX where paramId=52 and val<15)

union

(select grpId  from tableX where paramId=188 and val<= 269
intersect
select grpId from tableX where paramId=189 and val<= 298)

union

select grpId from tableX where paramId=123 and val<1.29