2012-09-08 41 views
3

我無法解決這個問題很多小時。
這是我的表如何將結果與條件分組?

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 | 
––––––––––––––––––––––––––––––––––– 
... 
+1

'...按屬性值,值1,值2'? –

+0

@MarcB:仔細看看這個問題,我不認爲就是這樣。標題具有誤導性。如我錯了請糾正我。 –

+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.

+0

這正是我需要的!非常感謝! –

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