我有一個表結構(我沒有設計也不能更改),它使用varchar
字段來存儲關於實體的屬性。我想編寫一個SQL查詢來特別搜索兩個屬性,並將多個結果行合併爲單個行。爲了說明這一點,我的表與此類似:Oracle group by SQL查詢通過匹配varchar字段
company
=============
| id | name |
-------------
| 1 | co1 |
| 2 | co2 |
| 3 | co3 |
=============
agent
====================================
| id | name | company_id | type |
------------------------------------
| 1 | Tom | 1 | 'type1' |
| 2 | Bob | 1 | 'type2' |
| 3 | Bill | 2 | 'type1' |
| 4 | Jack | 2 | 'type2' |
| 5 | John | 3 | 'type1' |
| 6 | Joe | 3 | 'type2' |
====================================
type1
和type2
是硬編碼到軟件作爲有效值(再次,我沒有寫它),所以對於這些值的搜索應該是成功的(允許爲空)。所以,我必須將我的搜索建立在這些值的基礎上。
作爲一個新手,我可以寫這樣的SQL:
select c.name, a.name, a.type
from company c
inner join agent a on c.id = a.company_id
,並分類整理這些結果在我的軟件(Java程序):
===========================
| c.name | a.name | type |
---------------------------
| co1 | Tom | type1 |
| co1 | Bob | type2 |
| co2 | Bill | type1 |
| co2 | Jack | type2 |
| co3 | John | type1 |
| co3 | Joe | type2 |
===========================
但是,我希望會有一個將行組合成更有效率的方式:
-- my failed attempt at writing this query
select c.name, a.name as type_1_agent, a.name as type_2_agent
from company c
inner join agent a on c.id = a.company_id
group by c.id -- ?
where -- ?
results:
======================================
| name | type_1_agent | type_2_agent |
--------------------------------------
| co1 | Tom | Bob |
| co2 | Bill | Jack |
| co3 | John | Joe |
======================================
這可能嗎?