开发者

sql query first rows with specific column values

i want to start by saying that i know there are a couple of questions regarding similar problems but they either dont answer my question fully or seem to be incompatible with SQLite.

I want to query all rows with value -1 and the first rows with values other than -1. And by "first rows" i mean the group of rows that are first with a certain value. the first row is the row that is first stumbled upon depending on开发者_如何转开发 the SORT BY clause

An example of the data and outcome:

Data:

a   b   -1 
c   d    1
e   f    2
g   h    2
i   j    2 
k   l   -1

Result:

a   b   -1 
c   d    1
e   f    2
k   l   -1

And as said above, i am using a SQLite database


Do this as two separate queries, one of them containing an inline view; UNION the two

  select blah, blah from T where  ...
UNION
  select * from
  (
    select blah, blah from T where something else order by somecolumn limit 1
  )


With simple example:

> select * from ex1; 
+------+----------+
| id   | name     |
+------+----------+
|    1 | Pirate   |
|    2 | Monkey   |
|    3 | Ninja    |
|    4 | Spagheti |
|    5 | kumar    |
|    6 | siva     |
+------+----------+

> select * from ex1 union select "1", "sing" order by case name when 'sing' then 1 else 2 end, name;
+------+----------+
| id   | name     |
+------+----------+
| 1    | sing     |
| 5    | kumar    |
| 2    | Monkey   |
| 3    | Ninja    |
| 1    | Pirate   |
| 6    | siva     |
| 4    | Spagheti |
+------+----------+
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜