2015-10-26 2 views
-1

Мне нужно перекрестно ссылаться на эти 2 таблицы и отображать только совпадающие contindex из первой таблицы, если contindex из другой таблицы соответствует. Ниже приведен образ того, что у меня есть. Также код будет вставлен ниже.SQL как перекрестно ссылаться на две несвязанные таблицы

select t.ContIndex, t.clientcode, t.debttranname as ClientName, DebtDetService, 
case when DebtTranType = 3 then 'Invoice' else 'Credit Memo' end as Type, d.amount, 
REPLACE(REPLACE(REPLACE(CAST(FeeNarrative As varchar(max)), 
CHAR(10) + CHAR(13), ' '), CHAR(10), ' '), CHAR(13), ' ') as Narrative 
from tblTranDebtorDetail d 
inner join tbltrandebtor t on t.DebtTranIndex=d.DebtTranIndex 
where DebtTranDate > 'jan 1 2015' and t.debttrantype in (3,6) 
and DebtDetService = 'abr reimb' 

select w.contindex /*, ClientCode, ClientName, Job_Name, 
case when TransTypeIndex=1 then 'Time' else 'Exp' end as Type, sum(wipamount)*/ 
from tblTranWIP w 
inner join tblJob_Header h on h.job_idx=w.ServPeriod and h.ContIndex=w.ContIndex 
inner join tblengagement e on e.ContIndex=w.ContIndex 
inner join tblstaff s on s.StaffIndex=w.StaffIndex 
where wipoutstanding <>0 and h.Job_Template in (99,100) and TransTypeIndex in (1,2) 
--group by w.contindex, ClientCode, ClientName, Job_Name, TransTypeIndex 

Preview of what I have

В основном нужно показать только верхние строки таблицы, которые соответствуют нижней таблице contindex.

+0

Вы можете изменить любой запрос? – JamieD77

ответ

3

Похоже, что таблицы связаны contindex, нет? Во всяком случае, скопировать и вставить код и добавив лишь немного больше следует сделать трюк:

select t.ContIndex, t.clientcode, t.debttranname as ClientName, DebtDetService, 
case when DebtTranType = 3 then 'Invoice' else 'Credit Memo' end as Type, d.amount, 
REPLACE(REPLACE(REPLACE(CAST(FeeNarrative As varchar(max)), 
CHAR(10) + CHAR(13), ' '), CHAR(10), ' '), CHAR(13), ' ') as Narrative 
from tblTranDebtorDetail d 
inner join tbltrandebtor t on t.DebtTranIndex=d.DebtTranIndex 
where DebtTranDate > 'jan 1 2015' and t.debttrantype in (3,6) 
and DebtDetService = 'abr reimb' 
and t.ContIndex IN 
(

    select w.contindex /*, ClientCode, ClientName, Job_Name, 
    case when TransTypeIndex=1 then 'Time' else 'Exp' end as Type, sum(wipamount)*/ 
    from tblTranWIP w 
    inner join tblJob_Header h on h.job_idx=w.ServPeriod and h.ContIndex=w.ContIndex 
    inner join tblengagement e on e.ContIndex=w.ContIndex 
    inner join tblstaff s on s.StaffIndex=w.StaffIndex 
    where wipoutstanding <>0 and h.Job_Template in (99,100) and TransTypeIndex in (1,2) 
    --group by w.contindex, ClientCode, ClientName, Job_Name, TransTypeIndex 
) 

Дополнительный код является WHERE t.contindex IN (<yoursecondquery>) Вы могли бы сделать то же самое с INNER JOIN тоже, но это быстродействую- исправить, учитывая, что вы уже отправили оба запроса отдельно.

+0

Да, я не имел в виду «НЕ». Удалены! Спасибо – JNevill

+0

Спасибо за объяснение! Оно работает! – andres

2

Здесь вы можете использовать IN или EXISTS. Вам просто нужно немного изменить второй запрос, чтобы добавить условие WHERE, если вы используете EXISTS.

SELECT 
    t.ContIndex, 
    t.clientcode, 
    t.debttranname AS ClientName, 
    DebtDetService, 
    CASE WHEN DebtTranType = 3 THEN 'Invoice' 
     ELSE 'Credit Memo' 
    END AS Type, 
    d.amount, 
    REPLACE(REPLACE(REPLACE(CAST(FeeNarrative AS VARCHAR(MAX)),CHAR(10) + CHAR(13),' '),CHAR(10),' '),CHAR(13),' ') AS Narrative 
FROM 
    tblTranDebtorDetail d 
    INNER JOIN tbltrandebtor t ON t.DebtTranIndex = d.DebtTranIndex 
WHERE 
    DebtTranDate > 'jan 1 2015' 
    AND t.debttrantype IN (3,6) 
    AND DebtDetService = 'abr reimb' 
    AND EXISTS (SELECT 
        w.contindex 
       FROM 
        tblTranWIP w 
        INNER JOIN tblJob_Header h ON h.job_idx = w.ServPeriod 
                AND h.ContIndex = w.ContIndex 
        INNER JOIN tblengagement e ON e.ContIndex = w.ContIndex 
        INNER JOIN tblstaff s ON s.StaffIndex = w.StaffIndex 
       WHERE 
        t.ContIndex = w.contindex -- new where clause 
        AND wipoutstanding <> 0 
        AND h.Job_Template IN (99,100) 
        AND TransTypeIndex IN (1,2)) 
+0

Этот метод также работает! Спасибо! – andres

Смежные вопросы