简体   繁体   中英

How to select similar values together in same query?

I have the database as below, i need to get all the zeros and ones in separate list from the below table, that is to get all the zero together in a column and all the ones together in separate column

database

| id | value |
-------------
| 1  |   0   |
| 2  |   1   |
| 3  |   0   |
| 4  |   1   |

expected result

| sp.id | stop | st.id | start|
-------------------------------
|   1   |   0  |   2   |   1  |
|   3   |   0  |   4   |   1  |

or

| id | value |
-------------
| 1  |   0   |
| 3  |   0   |


| id | value |
-------------
| 2  |   1   |
| 4  |   1   |
SELECT a.id AS sp.id, a.value AS stop, b.id AS st.id, b.value AS start
FROM (SELECT * FROM TABLE WHERE = 0) a
LEFT JOIN (SELECT * FROM TABLE WHERE = 1) b
ON a.id = b.id
UNION
SELECT a.id AS sp.id, a.value AS stop, b.id AS st.id, b.value AS start
FROM (SELECT * FROM TABLE WHERE = 0) a
RIGHT JOIN (SELECT * FROM TABLE WHERE = 1) b
ON a.id = b.id

For your expected result 1, you can use case

select case when value=0 then id end as spid,
       case when value=0 then value end as stop,
       case when value=1 then id end as stid,
       case when value=1 then value end as start
from yourtable.

But you will get NULL for empty rows as shown below. If that is fine, you can use the above query. If it is a String you can use MAX() or MIN() with group by to avoid this empty values.

OUTPUT

+------+------+------+-------+
| spid | stop | stid | start |
+------+------+------+-------+
| 1    | 0    |      |       |
+------+------+------+-------+
|      |      | 2    | 1     |
+------+------+------+-------+
| 3    | 0    |      |       |
+------+------+------+-------+
|      |      | 4    | 1     |
+------+------+------+-------+

For you expected output 2, you can directly use UNION ALL

select id,value from test where value=0
union all
select id,value from test where value=1

OUTPUT

+----+-------+
| id | value |
+----+-------+
| 1  | 0     |
+----+-------+
| 3  | 0     |
+----+-------+
| 2  | 1     |
+----+-------+
| 4  | 1     |
+----+-------+

CHECK DEMO HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM