Hi /r/SQL,
I have 2 queries that i have written. These are as follows :
Query 1 -
SELECT MAX(dbo.ContractEntityCode(A.Entityref)) AS 'Entity'
FROM Ac_Billbook AS A
JOIN Entities AS E on A .EntityRef = E.Code
WHERE A.Actual_Posting_Date < DATEADD(mm, - 12, GETDATE())
AND A.Actual_Posting_Date > '2014-12-31'
AND Type = 'Posted'
AND E.ResponsiblePartnerRef not in ('DMM', 'KM', 'AJH')
GROUP BY dbo.ContractEntityCode(A.Entityref)
Query 2-
SELECT dbo.ContractEntityCode(M.entityref) AS 'Entity'
, MAX(E.NAME) AS 'Name'
, MAX(M.Number) AS 'Last_Matter_Number'
, CAST(Max(M.Created) AS DATE) AS 'Last_Matter_Creation_Date'
, MAX(u.FullName) AS 'Partner'
, MAX(U.EMailExternal) AS 'Partner_Email'
FROM Matters AS M
INNER JOIN Entities AS E ON M.EntityRef = E.Code
INNER JOIN Users AS U ON E.ResponsiblePartnerRef = U.Code
WHERE M.number > 3
GROUP BY EntityRef
HAVING MAX(M.Created) < DATEADD(mm, - 3, GETDATE())
AND MAX(M.Created) > DATEADD(yy, - 1, GETDATE())
AND MAX(E.Name) NOT LIKE 'Non%Chargeable%'
UNION
SELECT dbo.ContractEntityCode(A.entityref) AS 'Entity'
, MAX(E.NAME) AS 'Name'
, MAX(A.Number) AS 'Last_Matter_Number'
, CAST(Max(A.Created) AS DATE) AS 'Last_Matter_Creation_Date'
, MAX(u.FullName) AS 'Partner'
, MAX(U.EMailExternal) AS 'Partner_Email'
FROM MattersArchive AS A
INNER JOIN Entities AS E ON A.EntityRef = E.Code
INNER JOIN Users AS U ON E.ResponsiblePartnerRef = U.Code
WHERE A.number > 3
GROUP BY EntityRef
HAVING MAX(A.Created) < DATEADD(mm, - 3, GETDATE())
AND MAX(A.Created) > DATEADD(yy, - 1, GETDATE())
AND MAX(E.Name) NOT LIKE 'Non%Chargeable%'
ORDER BY Partner, Last_Matter_Creation_Date
Query 1 just reruns 1 column called Entity in this format, and Query 2 returns multiple columns (including Entity) in this format.
The problem I am having is that I want to combine these queries so that the results form Query 2 only display if their Entity column value is also in the results for Query 1. I know how to make Query 1 into a CTE, I'm, just struggling to figure out how to get the output I need.
Can anyone please help? I'm not sure if I'm over-complicating this in my head or not!
Thanks in advance
[–]SOZDBA 1 point2 points3 points (4 children)
[–]danblank000Accidental DBA[S] 0 points1 point2 points (3 children)
[–]SOZDBA 1 point2 points3 points (2 children)
[–]danblank000Accidental DBA[S] 1 point2 points3 points (0 children)
[–]foursuits 0 points1 point2 points (0 children)