I need to join data from multiple databases (on the same server). That in itself doesn’t seem to be inherently difficult. However, I have a CTE that iterates down to get all the children of a specified group. Below I have two distinct queries. The first one has the proper lineage and the second one gets the proper data. What I don’t understand is how to combine these two using the lineage of the first query.
Query 1
This is the lineage I need (where f_locationID = some ID passed from the web app). This works as desired and gives me all the machines that belong to the location or machines that belong to children of the location. However, the data I need for these machines resides in another database entirely.
;with cte_assets as (
select a.f_locationid, a.f_locationparent, a.f_locationname, 0 as [lev], convert(varchar(30), '0_' + convert(varchar(10), f_locationid)) lineage
from [db_assets].[dbo].[tb_locations] a where f_locationID = '130' UNION ALL
select a.f_locationid
,a.f_locationparent
,a.f_locationname
,c.[lev] + 1
,convert(varchar(30), lineage + '_' + convert(varchar(10), a.f_locationid))
from cte_assets c
join [db_assets].[dbo].[tb_locations] a
on a.f_locationparent = c.f_locationID
)
select f_assetnetbiosname as 'Computer Name'
from cte_assets c
JOIN tb_assets ass on ass.f_assetlocation = c.f_locationID
ORDER BY f_assetname DESC
Query 2
This is the data I need. The CTE here can be discarded as the lineage was set up merely as an example, and is not what I need. See the results window below to see the data. However, I’d like that data back out for the lineage from above (where ‘Computer Name’ from query 2 = ‘Computer Name’ from query 1).
;with rCTE as (
select a.f_itemid
,a.f_itemparentid
,a.f_itemtype
,a.f_itemname
,0 as [lev]
,convert(varchar(30), '0_' + convert(varchar(10), f_itemid)) lineage
from [db_reports].[dbo].[tb_locationsmachines] a
where f_itemid = '1308'
UNION ALL
select a.f_itemid
,a.f_itemparentid
,a.f_itemtype
,a.f_itemname
,c.[lev] + 1
,convert(varchar(30), lineage + '_' + convert(varchar(10), a.f_itemid))
from rCTE c
join [db_reports].[dbo].[tb_locationsmachines] a
on a.f_itemparentid = c.f_itemid
)
--below is what I need, not the lineage above
SELECT f_computername as 'Computer Name',
SUM(f_sessionlength) AS 'Total Session Time',
COUNT(*) as 'Sessions',
COUNT(*)/60 as 'Average Sessions per Day',
CAST(SUM(f_sessionlength) / 3600E / COUNT(*) as DECIMAL(18,2)) as 'Average Session Length (Hours)'
from rCTE c
JOIN [db_reports].[dbo].[tb_sessions] ss on ss.f_computername = c.f_itemname
GROUP BY f_computername
Order By 'Sessions' DESC, f_computername ASC
The common field between the two tables is ‘Computer Name’. I think I need a CTE inside a CTE, but no matter what I try I cannot get it to work.
Any guidance is greatly appreciated, sincerely.
Thanks in advance,
Matt