SQL Server Nesting a query that uses Inner Join to a larger query

nwlls2ji  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(96)

I'm trying to append some data to an existing query, but the additional data uses an Inner Join to work correctly. I am struggling to nest it without losing results in the larger query.

The original query is built from many tables, so it takes:

select
    T1.key1,
    T1.data1,
    T1.data2,
    T1.data3,
    T2.key1,
    T2.data1,
    T2.data2,
    T2.data3
    ...
from Table1 T1
JOIN Table2 ON T1.key1=T2Key1
JOIN
...

WHERE (criteria).

Then there is the second table comes in, where I tried getting the latest date that a specific action occurs by using the following:

select
    NewTable.Key1,
    NewTable.Data1,
    NewTable.Data2,
    NewTable.Data3,
    NewTable.Data4,
    NewTable.Data5,
    Table1.Data2,
    Table2.Data3
FROM tablename1 NewTable
INNER JOIN
(
    select Data1, MAX(date) AS DateTime
    FROM tablename1
    WHERE (criteria)
    GROUP BY Key1
) AS NewTable2 ON (NewTable.Key1 = NewTable2.Key1) AND (NewTable.Data1 = NewTable2.Data1)
LEFT JOIN Table 1...
LEFT JOIN Table 2...;

Now I want to include this table as part of the data gathering in the first table. I don't need the Table1 & Table2 data, as that is part of the table at the start, but I am struggling to include the second table without loss of data.

What would be the best approach to incorporate this additional data in, given that it needs an Inner Join, that must not impact on the previous data? In essence, I need all the data from the first query regardless of what the second query produces, but the second query needs to be limited to produce the right results?

So far I am using Power Bi to merge the two resulting tables, but wondering if there's a more efficient wat.

vnjpjtjt

vnjpjtjt1#

You can just union both the result set,

select
    T1.key1,
    T1.data1,
    T1.data2,
    T1.data3,
    T2.key1,
    T2.data1,
    T2.data2,
    T2.data3
    ...
from Table1 T1
JOIN Table2 ON T1.key1=T2Key1
JOIN
...

WHERE (criteria)

Union all

select
    NewTable.Key1,
    NewTable.Data1,
    NewTable.Data2,
    NewTable.Data3,
    NewTable.Data4,
    NewTable.Data5,
    Table1.Data2,
    Table2.Data3
FROM tablename1 NewTable
INNER JOIN
(
    select Data1, MAX(date) AS DateTime
    FROM tablename1
    WHERE (criteria)
    GROUP BY Key1
) AS NewTable2 ON (NewTable.Key1 = NewTable2.Key1) AND (NewTable.Data1 = NewTable2.Data1)
LEFT JOIN Table 1...
LEFT JOIN Table 2...;

相关问题