0

I have a table with this structure:

+------------+-----------------+----------+
| xreference |      title      | language |
+------------+-----------------+----------+

I want that to obtain something like this by means of an SQL query :

+------------+---------------+-----------------+--------------+--------------+
| xreference |   title_eng   |    title_ita    | language_eng | language_ita |
+------------+---------------+-----------------+--------------+--------------+

how can i obtain this structure? There is a method that allow to organize two records of the same table in the same row?

For example, if i have this data:

+------------+-----------------+----------+
| xreference |      title      | language |
+------------+-----------------+----------+
|          1 | example_title   | eng      |
|          1 | example_title_2 | ita      |
+------------+-----------------+----------+

i want to obtain something like this:

+------------+---------------+-----------------+--------------+--------------+
| xreference |   title_eng   |    title_ita    | language_eng | language_ita |
+------------+---------------+-----------------+--------------+--------------+
|          1 | example_title | example_title_2 | eng          | ita          |
+------------+---------------+-----------------+--------------+--------------+
madmad
  • 9
  • 7

2 Answers2

2

The simplest way in your case is probably conditional aggregation:

select xreference,
       max(case when language = 'eng' then title end) as title_eng,
       max(case when language = 'ita' then title end) as title_ita,
       'eng' as language_eng, 'ita' as language_ita
from thisdata t
group by xreference;

I am not sure what the last two columns are supposed to be doing.

The advantage to this method over using a join is two-fold. First, it is easy to add new languages. And, this will show all xreference values, even those that have no translations in English and/or Italian.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I want all the values stored in my table not only max (or min or count). It is possible to perform this conditional aggregation without these operators? – madmad Jun 09 '15 at 14:47
  • @madmad, this will give you max of one value, i.e. the only value! – jarlh Jun 09 '15 at 14:57
  • @madmad . . . This assumes that there is at most one English title and at most one Italian title for each `xreference`. If this is not true, you might want `group_concat()` instead. – Gordon Linoff Jun 10 '15 at 02:07
0

do a self join but without the subselect:

SELECT t1.title as title_eng, t2.title as title_ita
from table1 t1
join table2 t2 on (t2.xreference = t1.xreference)
where t1.language = 'eng' and t2.language = 'ita'