简体   繁体   中英

SQL Select for unique value in a column

I have a table like

| ID | COL1 | COL2 |
| 1  |   1  |  w   |
| 1  |   2  |  x   |
| 2  |   1  |  y   |
| 2  |   2  |  z   |

When I query it, I'd like to get

| ID | COL2:1 | COL2:2 |    <--- (when COL1=1 and COL1 =2)
| 1  |   w    |    x   |
| 2  |   y    |    z   |

I've tried GROUP BY and JOIN for the same table but I get duplicates and not grouped data. I need some pointers for how to get the results I'm expecting.

You can use MAX() and a CASE statement for this:

SELECT ID
      ,MAX(CASE WHEN Col1 = 1 THEN Col2 END) AS Col2_1
      ,MAX(CASE WHEN Col1 = 2 THEN Col2 END) AS Col2_2
FROM YourTable
GROUP BY ID

Demo: SQL Fiddle

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