2015-11-24 58 views
0

我有一個表結構(我沒有設計也不能更改),它使用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' | 
==================================== 

type1type2是硬編碼到軟件作爲有效值(再次,我沒有寫它),所以對於這些值的搜索應該是成功的(允許爲空)。所以,我必須將我的搜索建立在這些值的基礎上。

作爲一個新手,我可以寫這樣的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 | 
====================================== 

這可能嗎?

回答

0

你可以用透視功能做到這一點,就像這樣:

select company,type_1_agent,type_2_agent 
from 
(select a.name as agentname, a.type as agenttype,c.name as company 
from agent a 
inner join company c on c.id = a.company_id 
) s 
pivot 
(max(agentname) for agenttype in ('type1' type_1_agent,'type2' type_2_agent)) p 
order by company 

Demo

當然,在這種情況下,我們硬編碼類型的值。這可以變爲動態以適應這些值的未知數。

0

Oracle版本:

WITH company (id, name) AS (
    SELECT 1, 'co1' FROM DUAL UNION ALL 
    SELECT 2, 'co2' FROM DUAL UNION ALL 
    SELECT 3, 'co3' FROM DUAL 
), 
agent (id, name, company_id, type) AS (
    SELECT 1, 'Tom', 1, 'type1' FROM DUAL UNION ALL 
    SELECT 2, 'Bob', 1, 'type2' FROM DUAL UNION ALL 
    SELECT 3, 'Bill', 2, 'type1' FROM DUAL UNION ALL 
    SELECT 4, 'Jack', 2, 'type2' FROM DUAL UNION ALL 
    SELECT 5, 'John', 3, 'type1' FROM DUAL UNION ALL 
    SELECT 6, 'Joe', 3, 'type2' FROM DUAL 
) 
SELECT 
    company_name, type_1_agent, type_2_agent 
FROM 
    (SELECT company.name company_name, agent.name agent_name, type FROM company JOIN agent ON company.id = agent.company_id) 
    PIVOT (
     MAX(agent_name) agent 
     FOR type IN ('type1' type_1, 'type2' type_2) 
    ) 
ORDER BY 
    company_name