Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Say I have a table of the form:

+-----+-------+
| Key | Value |
+-----+-------+
| A   |     1 |
| A   |     3 |
| A   |     4 |
| B   |     2 |
| B   |     3 |
| C   |     3 |
| C   |     4 |
| C   |     5 |
+-----+-------+

I want to be able to return all of the keys that have at least a given range.

For example:

A query for a Value range of 2 would return A, B, C
A query for a Value range of 3 would return A, C
A query for a Value range of 4 would return A

Can this be done with SQL (specifically SQLite)? If so, how?

share|improve this question
    
What if the value has gaps? Is a range of 4 a contiguous series of 4 values? Or just the difference between MIN and MAX for that key? –  Martin Smith Jan 19 at 22:56
    
It's the difference between MIN and MAX for that key. I've updated the question to reflect this. –  Jamie Bullock Jan 19 at 23:08

1 Answer 1

up vote 2 down vote accepted

To find those with a "range" of at least 4 for example

SELECT "Key"
FROM   YourTable
GROUP  BY "Key"
HAVING (1 + MAX("Value") - MIN ("Value")) >= 4; 

Obviously alter the 4 as appropriate for the other cases.

SQL Fiddle

share|improve this answer
    
Perfect, thanks! –  Jamie Bullock Jan 20 at 0:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.