Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a query like this?

Tags:

sql

mysql

pivot

I have a table like this on mySQL db:

Olimpiade     Sport        Disciplina   Categoria
---------------------------------------------------
London 2012   Athletics    100m         men
London 2012   Athletics    100m         woman
Beijing 2008  Athletics    200m         men
Beijing 2008  Athletics    200m         women
Athens 2004   Athletics    800m         men
Athens 2004   Athletics    800m         women

and so on. I don't know if I could set up a query like this, but what I would like to get is a result as follow:

Disciplina   Categoria   London 2012    Beijing 2008   Athens 2004
------------------------------------------------------------------
100m         men         yes            no             yes
100m         women       yes            yes            no
200m         men         yes            no             yes
200m         women       yes            yes            no
800m         men         yes            yes            yes
800m         women       yes            yes            yes

that is if the trial is present or not for that olympics edition.

like image 930
Idro Avatar asked Feb 07 '16 12:02

Idro


People also ask

Can you do a like in statement in SQL?

There is no combination of LIKE & IN in SQL, much less in TSQL (SQL Server) or PLSQL (Oracle). Part of the reason for that is because Full Text Search (FTS) is the recommended alternative.

Can we use multiple like in SQL?

No, MSSQL doesn't allow such queries.


Video Answer


1 Answers

Yes you can, use CASE like this,

Select Disciplina, Categoria, 
CASE when Olimpiade = 'London 2012' then 'yes' else 'no' end as 'London 2012', 
CASE when Olimpiade = 'Beijing 2008' then 'yes' else 'no' end as 'Biejing 2008',
CASE when Olimpiade = 'Athens 2004' then 'yes' else 'no' end as 'Athens 2004'    from tableName group by Disciplina, Categoria order by Disciplina, Categoria
like image 184
digitai Avatar answered Oct 24 '22 15:10

digitai