2015-06-26 59 views
0

我想查询一个企业的SQL ServerSQL多次查找在一个SQL查询中的单码列

无论出于何种原因claim_IdStatus_ID都包含在同一个表,我想在翻译claim_IDStatus ID相同的查询作为单独的列我该怎么做?

╔═══════════╦═════════╗ 
║ claim ║ code ║ 
╠═══════════╬═════════╣ 
║ claim_ID ║ code_ID ║ 
║ status_ID ║ name ║ 
╚═══════════╩═════════╝ 

Claim表:

╔═══════════╦═════════╗═════════╗ 
║ Claim_ID ║status_ID║Item_ID ║ 
╠═══════════╬═════════╣═════════║ 
║ 1   ║ 12  ║ 1  ║ 
║ 2   ║ 14  ║ 2  ║ 
╚═══════════╩═════════╝═════════ 

Code表:

╔═══════════╦═════════╗ 
║ CODE ID ║ name ║ 
╠═══════════╬═════════╣ 
║ 1   ║ complete║ 
║ 2   ║ cancel ║ 
║ 12  ║ Open ║ 
║ 14  ║Shipping ║ 
╚═══════════╩═════════╝ 

理想输出:

╔═══════════╦════════════ ╗════════════════ 
║ ITEM_ID ║Claim_ID_name║status_ID_name ║ 
╠═══════════╬═════════════╬═══════════════╣ 
║ 1   ║ complete ║ open  ║  
║ 2   ║ cancel  ║ shipping ║ 
║   ║    ║    ║ 
║   ║    ║    ║ 
╚═══════════╩═════════════════════════════╝ 
+1

请张贴一些示例数据和所需的输出。很可能你需要使用CASE结构。 –

+1

请描述更好,并显示示例数据 – Drew

+0

嘿家伙很抱歉,即时通讯新的堆栈溢出试图尽可能清楚 –

回答

0

使用子查询:

SELECT 
    ITEM_ID, 
    (SELECT name FROM Code WHERE CODE_ID = Claim_ID) AS Claim_ID_NAME, 
    (SELECT name FROM Code WHERE CODE_ID = status_ID) AS status_ID_name 
FROM Claim 
+0

感谢您的Eric证明是最有效的解决方案我做了一些子查询研究结果 –

0

试试这个。

select item_id, code_table.name, sub_table.name 
from claim_table, code_table, 
(select code_id, name 
from code_table 
) sub_table        
where claim_id = code_table.code_id 
and status_id = sub_table.code_id; 

您也可以尝试去探索子查询:

http://www.tutorialspoint.com/sql/sql-sub-queries.htm

http://beginner-sql-tutorial.com/sql-subquery.htm

希望它能帮助。

+0

你可以试试这个,但是,我认为@ Eric的答案会执行得更快,因为它消耗更少的成本。 – user3462803