[英]SQL: Select column as <another column's value>
我有一張桌子
ID | LanguageID | Text
1 | 1 | Abc
1 | 2 | Def
我想選擇數據,以便將具有相同ID的所有行分組為一行,並將每個文本選擇為具有其LanguageID名稱的列。 在這個特定的例子中,結果將是
[ID: 1, 1: 'Abc', 2: 'Def']
可以這樣做嗎? 怎么樣? 謝謝
我正在使用MySQL。
編輯:似乎最簡單的事情是編寫一個腳本來合並數據庫之外的行。
編輯2:我不知道接受什么答案,因為沒有一個工作或滿足上述要求。
如果您有固定數量的語言ID,那么您可以這樣做:
select id,
max(case when LanguageId = 1 then text end) as "1",
max(case when LanguageId = 2 then text end) as "2",
max(case when LanguageId = 3 then text end) as "3"
from t
group by id;
如果您事先不知道語言ID,則需要使用動態SQL構造查詢,然后准備並執行它。
如果languageid是動態的:
select @s = concat('select id',
group_concat(concat(', max(case when LanguageId = ',
LanguageId,
' then text end) as "',
LanguageId, '"'
)
),
' from t group by id'
)
from (select distinct LanguageId from t) t;
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
select id, group_concat(languageid), group_concat(text)
from t
group by id
要么
select id, group_concat(languageid, ':', text)
from t
group by id
select id, group_concat(languageid,':', text) as result
from table1
group by id
看看這個希望這是你正在尋找的: http : //sqlfiddle.com/#!2/159927/13
select id, group_concat(concat(languageid, ' ',text))
from t
group by id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.