2015-05-31 64 views
0

我有3個表:SQL查詢查找另一個表2倍的值

1) JCTransactions 
Job   CostCode Date  Amount 
36801-001 01-150  1/8/2015 55.00 
36801-001 02-240  2/6/2015 26.00 

2) JCCostCode 
Job   CostCode Description 
36801-001 01-000  Land 
36801-001 01-150  Land Legal Fees 
36801-001 02-000  Holding Costs 
36801-001 02-240  Property Taxes 

3) JCJob 
Job   Description 
36801-001 BusinessCenter1 
36901-001 BusinessCenter2(NotYetStarted) 

我想做一個查詢,顯示從JCTransactions表,但與職位描述,成本代碼說明中的所有記錄,並頂級成本代碼說明。

例如:

Job   CostCode Date  Amount JobDesc   CostCodeDesc TopLevelCostCode TopLevelCodeDesc 
36801-001 01-150  1/8/2015 55.00 BusinessCenter1 Land Legal Fees 01-000    Land 
36801-001 02-240  2/6/2015 26.00 BusinessCenter1 Property Taxes 02-000    Holding Costs 

我遇到麻煩TopLevelCostCode及其描述到的結果。

這裏是我到目前爲止的代碼效果很好,除了它沒有最後2列,我想:

SELECT JCTRANSACTIONS.Job, 
JCTRANSACTIONS.CostCode, 
JCTRANSACTIONS.Date, 
JCTRANSACTIONS.Amount, 
JCJOB.Description, 
JCCOSTCODE.Description 
FROM "\\Network\".JCCOSTCODE JCCOSTCODE, 
"\\ Network \".JCJOB JCJOB, 
"\\ Network \".JCTRANSACTIONS JCTRANSACTIONS 
WHERE 
JCJOB.Job = JCTRANSACTIONS.Job AND 
JCCOSTCODE.Cost_Code = JCTRANSACTIONS.Cost_Code AND 
JCCOSTCODE.Job = JCJOB.Job AND 
JCCOSTCODE.Job = JCTRANSACTIONS.Job 
+0

你怎麼知道還會有JCCostCode正好兩行各JCJob ? – Jasen

+0

對於每個JCJob,不一定要有2行JCCostCode。 JCJob可以有多個JCCostCode。但是每個JCCostCode都會有一行以-000結尾作爲頂級成本代碼。 (例如01-000是01-150的頂級代碼)。爲了澄清,WHERE之後的條件被MS Query放入,我沒有寫這些查詢,因此它可能不正確。 – martin

回答

0
select * from JCCOSTCODE 
select * from JCJOB 
select * from JCTRANSACTIONS 

select Res1.job,Res1.costcode,res1.date,res1.amount,res1.jobdesc,res1.costdesc,res2.topLevelCode,res2.TopLevelCodeDesc from (
SELECT JCTRANSACTIONS.Job, 
JCTRANSACTIONS.CostCode, 
JCTRANSACTIONS.Date, 
JCTRANSACTIONS.Amount, 
JCJOB.Description jobdesc, 
JCCOSTCODE.Description as costdesc , 
row_number() over(order by JCTRANSACTIONS.CostCode) rowid 
FROM JCCOSTCODE JCCOSTCODE 
inner join JCJOB JCJOB on JCCOSTCODE.Job = JCJOB.Job 
inner join JCTRANSACTIONS JCTRANSACTIONS on JCJOB.Job = JCTRANSACTIONS.Job and JCCOSTCODE.CostCode = JCTRANSACTIONS.CostCode) Res1 inner join (
select costcode as topLevelCode, Description as TopLevelCodeDesc, ROW_NUMBER() over (order by costcode) rowid from JCCOSTCODE where costcode not in (select costcode from JCTRANSACTIONS)) res2 
on Res1.rowid = Res2.rowid