如何根据条件对结果进行分组?

时间:2012-09-08 13:12:29

标签: mysql

我无法解决这个问题很长时间 这是我的表

t1:

–––––––––––––––––––––––––––––––––––
| id | text   |  lang | transl_id |
–––––––––––––––––––––––––––––––––––
| 1  | first  |  en   |  222      |
–––––––––––––––––––––––––––––––––––
| 2  | second |  de   |  222      |
–––––––––––––––––––––––––––––––––––
| 3  |   jkj  |  de   |  234      |
–––––––––––––––––––––––––––––––––––
| 4  |  89080 |  de   |  235      |
–––––––––––––––––––––––––––––––––––

这是我的问题:

SELECT
    transl_id AS property,
    (SELECT text FROM t1 WHERE lang='en') AS value1,
    (SELECT text FROM t1 WHERE lang='de') AS value2,

FROM t1

返回以下表格:

–––––––––––––––––––––––––––––––––––
| property  |  value1  |  value2  |
–––––––––––––––––––––––––––––––––––
|    222    |  first   |          |
–––––––––––––––––––––––––––––––––––
|    222    |          |  second  |
–––––––––––––––––––––––––––––––––––
|    234    |  jkj     |          |
–––––––––––––––––––––––––––––––––––
|    235    |  89080   |          |
–––––––––––––––––––––––––––––––––––

每行都有value1value2,而不是两者。有没有办法对结果进行分组,以便property字段的值相等的行在一行中?我的意思是这样的:

–––––––––––––––––––––––––––––––––––
| property  |  value1  |  value2  |
–––––––––––––––––––––––––––––––––––
|    222    |  first   |  second  |
–––––––––––––––––––––––––––––––––––
...

2 个答案:

答案 0 :(得分:3)

尝试此查询:

SELECT
    property,
    max(value1) as Value1,
    max(value2) as Value2
FROM 
(
SELECT transl_id AS property,
    CASE when lang = 'en' then text else null end as value1,
    CASE when lang = 'de' then text else null end as value2
FROM t1
) t
GROUP BY property

See this SQLFiddle

尝试在表格中添加更多值并获得所需的结果in this SQLFiddle.

答案 1 :(得分:0)

可能是这样的:

select t1.property, t1.value1, t2.value2 from
( select property, value1 from table1 where value1 is not null ) t1,
( select property, value2 from table1 where value2 is not null ) t2
where t1.property = t2.property