how to limit row number to one unique row in SQL query? - sql

I need to limit the row number to one unique row in SQL query. Here's sample data to recognize what I'm talking about:
john doe 3000 fog horn drive , ky 40444
john doe 3001 merry lane , ky 40484
I want to return the first one in the list here's my query :
Select
DISTINCT p.personID, e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade, i.gender, p.studentNumber, e.citizenship, e.adult, i.birthdate,
e.disability1, e.disability2, ad.city, e.displacedHomemaker, e.homeSchooled,
e.localStudentNumber, e.migrant, e.modifiedDate, e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid, i.lastname, i.firstname, i.middlename, i.ssn,
ad.phone, ad.state, ad.zip, ad.addressLine1
FROM
Person p
LEFT join
Enrollment e ON e.personID = p.personID And isnull(e.noshow, 0) = 0
LEFT join
EnrollmentKY ky ON ky.enrollmentID = e.enrollmentID
LEFT join
[Identity] i ON i.identityID = p.currentIdentityID And i.personID = p.personID
INNER join
Calendar c ON c.calendarID = e.calendarID
INNER join
SchoolYear sy ON sy.endYear = c.endYear AND sy.active = 1
JOIN
staffMember Staff ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join
v_MailingAddress ad ON ad.personID = i.personID And ad.relatedBy = 'household'
And ad.endDate IS NULL And isnull(ad.secondary, 0) = 0
order by
i.lastname, i.firstname, i.middlename
edit: need to only pick first row in SQL code because I have a problem with people that have multiple addresses it puts two rows for them and i only need first row of data for the person that has multiple addresses.

If the personId is distinct for each of the records and they just have a different address, then you can add a field for the row_number() and then only select the records where the row_number = 1:
select *
from
(
Select p.personID,
e.citizenship,
rtrim(i.lastname + CASE WHEN i.suffix IS NULL THEN '' ELSE ' ' + i.suffix END) + ', ' + i.firstname + (CASE WHEN i.middlename IS NULL THEN '' ELSE ' ' + i.middlename END) StuName,
e.grade,
i.gender,
p.studentNumber,
e.citizenship,
e.adult,
i.birthdate,
e.disability1,
e.disability2,
ad.city,
e.displacedHomemaker,
e.homeSchooled,
e.localStudentNumber,
e.migrant,
e.modifiedDate,
e.modifiedByID,
rtrim(Staff.lastname + CASE WHEN Staff.suffix IS NULL THEN '' ELSE ' ' + Staff.suffix END) + ', ' + Staff.firstname + (CASE WHEN Staff.middlename IS NULL THEN '' ELSE ' ' + Staff.middleName END) Staffname,
Staff.personID Staffid,
i.lastname,
i.firstname,
i.middlename,
i.ssn,
ad.phone,
ad.state,
ad.zip,
ad.addressLine1,
row_number() over(partition by p.personid order by p.personid) rn -- add this field
FROM Person p
LEFT join Enrollment e
ON e.personID = p.personID
And isnull(e.noshow,0)=0
LEFT join EnrollmentKY ky
ON ky.enrollmentID = e.enrollmentID
LEFT join [Identity] i
ON i.identityID = p.currentIdentityID
And i.personID = p.personID
INNER join Calendar c
ON c.calendarID = e.calendarID
INNER join SchoolYear sy
ON sy.endYear = c.endYear
AND sy.active = 1
JOIN staffMember Staff
ON Staff.personID = e.modifiedByID
--join view_students s ON s.personID = i.personID
left join v_MailingAddress ad
ON ad.personID = i.personID
And ad.relatedBy = 'household'
And ad.endDate IS NULL
And isnull(ad.secondary,0)=0
) x
where x.rn = 1
order by x.lastname, x.firstname, x.middlename

Try using the LIMIT to limit the no. of outputs.
Eg:
SELECT COLUMN_NAME
FROM TABLE
ORDER BY CONDITION
LIMIT NO_OF_ROWS;

Have you tried using a "GROUP BY" clause instead of the DISTINCT keyword?
Also, what about a Sub-Query? If I were writing this type of thing I'd use a sproc and create a temporary table.

Edit: Deleted original answer as question was changed and original answer is not the way to go with changed question.
Suggest GROUP BY clause per Neil Hoskins.

Related

Why is this sql query running so slowly? Large table with detailed string filter

The query below is running on a ~20000 row table. Each customer has 1-3 customer contacts. This particular query is taking more than 6 seconds to run despite only returning 11 rows. Which part is killing it?
SELECT C.Id,
CASE
WHEN CT.Name = 'Residential' THEN ISNULL(CC.FirstName, '') + ' ' + ISNULL(CC.LastName, '')
ELSE C.CompanyName
END AS FullName,
C.CustomerTypeId,
CT.Name,
ISNULL(CC.PhoneNumber, '') AS PhoneNumber,
A.City,
S.Name,
A.Street,
A.Zip,
C.TaxExempt,
C.Active,
ISNULL(C.CompanyName, '') AS CopmanyName,
ISNULL(CC.FirstName, '') AS CustomerContactFirstName,
ISNULL(CC.LastName, '') AS CustomerContactLastName
FROM [dbo].[Customer] C
JOIN Address A ON A.Id = C.AddressId
JOIN State S ON A.StateId = S.Id
JOIN CustomerType CT ON CT.Id = C.CustomerTypeId
LEFT OUTER JOIN CustomerContact CC ON CC.CustomerId = C.Id
AND CC.Active = 1
AND CC.[Primary] = 1
WHERE (0 = 1
OR C.Active = 1)
AND
(CT.Name +'|'+ ISNULL(CC.PhoneNumber,'') +'|'+ S.Name +'|'+ LTRIM(A.Street) + '|' + LTRIM(A.Zip)
+ CASE WHEN CT.Name = 'residential' THEN LTRIM(RTRIM(ISNULL(CC.FirstName, ''))) + ' ' + LTRIM(RTRIM(ISNULL(CC.LastName, ''))) ELSE '' END
+ CASE WHEN CT.Name != 'residential' THEN LTRIM(C.CompanyName) ELSE '' END
+ CASE WHEN C.TaxExempt = 1 THEN 'tax Exempt' ELSE '' END
+ CASE WHEN C.TaxExempt = 0 THEN 'taxable' ELSE '' END
+ CASE WHEN C.Active = 1 THEN 'active' ELSE '' END
+ CASE WHEN C.Active = 0 THEN 'not active' ELSE '' END
)
LIKE '%' + CASE WHEN lower('jake') = 'null' THEN '' ELSE lower('jake') END + '%'
ORDER BY FullName
OFFSET 0 ROWS -- skip rows
FETCH NEXT 150 ROWS ONLY; -- take rows
Basically like statement always costing time
in below query within case statement whichever record matching case condition it will return first so no need to search for other conditions
Hope so you got your answer
SELECT C.Id,
CASE
WHEN CT.Name = 'Residential' THEN ISNULL(CC.FirstName, '') + ' ' + ISNULL(CC.LastName, '')
ELSE C.CompanyName
END AS FullName,
C.CustomerTypeId,
CT.Name,
ISNULL(CC.PhoneNumber, '') AS PhoneNumber,
A.City,
S.Name,
A.Street,
A.Zip,
C.TaxExempt,
C.Active,
ISNULL(C.CompanyName, '') AS CopmanyName,
ISNULL(CC.FirstName, '') AS CustomerContactFirstName,
ISNULL(CC.LastName, '') AS CustomerContactLastName
FROM [dbo].[Customer] C
JOIN Address A ON A.Id = C.AddressId
JOIN State S ON A.StateId = S.Id
JOIN CustomerType CT ON CT.Id = C.CustomerTypeId
LEFT OUTER JOIN CustomerContact CC ON CC.CustomerId = C.Id
AND CC.Active = 1
AND CC.[Primary] = 1
WHERE (#VARIABLE1 = 1
OR C.Active = 1)
AND CASE WHEN isnull(#variable,'') !='' THEN
CASE WHEN Lower(C.CompanyName) like '%' + lower(#variable)+'%' THEN 1
WHEN Lower(CC.FirstName) like '%' + lower(#variable)+'%' THEN 1
WHEN Lower(CC.LastName) like '%' + lower(#variable)+'%' THEN 1
ELSE 0 END
ELSE 0 END =1
ORDER BY FullName
OFFSET 0 ROWS -- skip rows
FETCH NEXT 150 ROWS ONLY; -- take rows
You should look at the execution plan. Your request is not sargeable, which means you don't use indexes correctly.
First, don't use functions in the where clause (case, lower, isnull...). You should have calculated columns with indexes on them instead if you can't already insert good datas into the columns.
Try avoiding like '%xxxxxx'. Non sargeable if the percent isn't at the end of the string.
Avoid using left join. Sometimes it is better to do your request and store results into a temporary table and then use a left join on it.
Finally, you should try some indexes with included columns.

Filter based on where condition

I have a query where I am getting data for some tickets.Now I need to put a where condition to get data where timediffsecs <> 0.I am unable to get the correct place to put where conditon..
Below is my code .Please help
WITH CTE
AS
(
SELECT cr.ref_num as 'TicketNumber',
isnull(requestor.last_name,'') + ', ' + isnull(requestor.first_name,'') as 'Requestor'
,ISNULL(cnt.last_name, '') + ', ' + ISNULL(cnt.first_name,'') as 'Created By'
,isnull(aeu.last_name,'') + ', ' + isnull(aeu.first_name,'') as 'Affected End User',
isnull(logagent.last_name,'') + ', ' + isnull(logagent.first_name,'') as 'Reported By'
,dbo.ConvertUnixTime (cr.open_date) as 'Open Date'
,dbo.ConvertUnixTime (cr.last_mod_dt) as 'Last Modified Date'
,dbo.ConvertUnixTime (cr.resolve_date) as 'Resolve Date'
,dbo.ConvertUnixTime (cr.close_date) as 'Close Date'
,dbo.ConvertUnixTime (act.time_stamp) as 'systime',
cr.summary as 'Summary'
,convert(varchar(max),cr.[description]) as 'Description'
,act.[action_desc] as 'System Description'
,acttype.sym as 'Activity Type'
,act.time_spent as 'Time Spent',
ROW_NUMBER() OVER(PARTITION BY cr.ref_num ORDER BY dbo.ConvertUnixTime (act.time_stamp)) RN
-- ROW_NUMBER() OVER(ORDER BY dbo.ConvertUnixTime (act.time_stamp) ) RN
-- ROW_NUMBER generated based on ORDER BY Time DESC
-- You can also add case_id or any other column to generate
--ROW_NUMBER so that the time differences can be calculate
--based on other dimension.
from call_req cr with (nolock)
LEFT OUTER JOIN ca_contact requestor with (nolock) on cr.requested_by = requestor.Contact_uuid
LEFT OUTER JOIN ca_contact aeu with (nolock) on cr.customer = aeu.Contact_uuid
LEFT OUTER JOIN ca_contact logagent with (nolock) on cr.log_agent = logagent.Contact_uuid
INNER JOIN act_log act with (nolock) on cr.persid = act.call_req_id
INNER JOIN ca_contact cnt with (nolock) on act.analyst = cnt.contact_uuid
INNER JOIN act_type acttype with (nolock) on act.[type] = acttype.code
where cr.ref_num in ('23035883',
'23038276')
)
SELECT *,
CASE
WHEN A.RN = 3 THEN
DATEDIFF(
SECOND,
(SELECT systime FROM CTE WHERE RN = 2 AND TicketNumber= A.TicketNumber),
(SELECT systime FROM CTE WHERE RN = 3 AND TicketNumber= A.TicketNumber)
-- By setting RN = 3 and 2, I am calculating
-- Time differences between ROW 3 and 2
-- You can set it to any Row number as per your requirement
)
ELSE 0
END as timediffsecs
FROM CTE A
You just need to nest the current SELECT in a subquery:
WITH cte
....
SELECT *
FROM (
YourCurrentSelect
) q
WHERE q.timediffsecs <> 0

Why is this SQL Server query so slow?

This query takes 4 seconds to run, and it returns about 62000 rows. #c, #p and #a are strings made up of ints, separated by commas or empty, based on what needs to be filtered... unfortunately this can't be changed.
I have tried to run this without the filters and it does not make a difference.
I am fairly new to SQL.
The 3 common table expressions are there to take extra lines of code out.
I would like this to be able to run under a second if at all possible
DECLARE #UId int = '817',
#c varchar(max) = '',
#p varchar(max) = '',
#a varchar(max) = ''
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#FilteredData') IS NOT NULL
DROP TABLE #FilteredData;
WITH cteuag AS
(
SELECT
uag.CId,
uag.AuthorIsatIonGroupId,
rn = ROW_NUMBER() OVER (PARTITION BY uag.[UId], uag.CId, uag.AuthorIsatIonGroupId ORDER BY uag.CId)
FROM
uag
WHERE
uag.[UId] = #UId
AND uag.IsDeleted = 0
AND (#c = '' OR (#c LIKE CONVERT(varchar(4), uag.CId)
OR #c LIKE '%,' + CONVERT(varchar(4), uag.CId) + ',%'
OR #c LIKE CONVERT(varchar(4), uag.CId) + ',%'
OR #c LIKE '%,' + CONVERT(varchar(4), uag.CId))
)
),
cteuc AS
(
SELECT
uc.CId,
cteuag.AuthorIsatIonGroupId,
uc.[UId],
i.FirstName + Iif(i.MiddleName IS NOT NULL, ' ' + i.MiddleName + ' ', ' ') + i.Surname AS [AName],
rn = ROW_NUMBER() OVER (PARTITION BY uc.CId, uc.[UId] ORDER BY uc.ModifiedAt)
FROM
uc
INNER JOIN
cteuag ON cteuag.CId = uc.CId
AND uc.IsDeleted = 0
AND (#a = '' OR (#a LIKE CONVERT(varchar(4), uc.[UId])
OR #a LIKE '%,' + CONVERT(varchar(4), uc.[UId]) + ',%'
OR #a LIKE CONVERT(varchar(4), uc.[UId]) + ',%'
OR #a LIKE '%,' + CONVERT(varchar(4), uc.[UId]))
)
INNER JOIN
ui ON ui.[UId] = uc.[UId]
AND ui.IsDeleted = 0
INNER JOIN
i ON i.PId = ui.IndividualId
),
ctel AS
(
SELECT
la.LId,
p.CId,
la.[UId],
rn = ROW_NUMBER() OVER (PARTITION BY la.LId ORDER BY la.DateUpdated DESC)
FROM
la
INNER JOIN
p ON p.Id = la.PId
AND p.IsDeleted = 0
AND la.IsDeleted = 0
AND la.[UId] IS NOT NULL
INNER JOIN
l ON la.LId = l.Id
AND l.IsDeleted = 0
)
SELECT
c.Id AS CId,
c.[Name] AS CName,
u.Id AS AId,
cteuc.AName AS AName,
ctel.LId AS LId,
qh.Id AS QhId,
q.Id AS QId,
q.IsTrue AS isTrue,
p.Id AS PId,
p.[Name] AS PName,
qi.FinalCalculation AS Calculation
INTO
#FilteredData
FROM
c
INNER JOIN
cteuc ON cteuc.CId = c.Id
AND cteuc.Rn = 1
AND c.IsDeleted = 0
LEFT OUTER JOIN
u ON u.Id = Iif(cteuc.AuthorIsatIonGroupId = 1, #UId, cteuc.[UId])
AND u.IsDeleted = 0
LEFT OUTER JOIN
ctel ON ctel.CId = c.Id
AND ctel.Rn = 1
AND ctel.[UId] = u.Id
LEFT OUTER JOIN
(la
INNER JOIN
qla ON qla.LeadActivityId = la.Id
AND la.IsDeleted = 0
AND la.ActivityTypeId = 4
INNER JOIN
qh ON qla.QhId = qh.Id
AND qh.IsDeleted = 0
AND qh.IsReRated = 0
LEFT OUTER JOIN
(q
INNER JOIN
p ON p.Id = q.PId
AND q.IsDeleted = 0
AND p.IsDeleted = 0
) ON q.QhId = qh.Id) ON la.[UId] = u.Id
AND la.LId = ctel.LId
AND
(
#p = ''
OR
(
#p LIKE CONVERT(varchar(4), p.Id)
OR #p LIKE '%,' + CONVERT(varchar(4), p.Id) + ',%'
OR #p LIKE CONVERT(varchar(4), p.Id) + ',%'
OR #p LIKE '%,' + CONVERT(varchar(4), p.Id)
)
)
LEFT OUTER JOIN
(
SELECT
qi1.QId,
SUM(Iif(qi1.Calculation = 0, 0, qi1.Calculation + qi1.Extra)) AS FinalCalculation
FROM qi
WHERE qi1.IsDeleted = 0
GROUP BY QId
) AS qi ON qi.QId = q.Id
WHERE
(
#p = ''
OR
(
p.Id IS NOT NULL
OR qh.Id IS NULL
)
)
SELECT * FROM #FilteredData
EDIT:
just to be clear, the above query does not run any slower than this one:
DECLARE #UId int = '817'
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#FilteredData') IS NOT NULL DROP TABLE #FilteredData;
WITH cteuag AS
(
SELECT
uag.CId,
uag.AuthorIsatIonGroupId,
rn = ROW_NUMBER() OVER (PARTITION BY uag.[UId], uag.CId, uag.AuthorIsatIonGroupId ORDER BY uag.CId)
FROM uag
WHERE uag.[UId] = #UId
AND uag.IsDeleted = 0
),
cteuc AS
(
SELECT
uc.CId,
cteuag.AuthorIsatIonGroupId,
uc.[UId],
i.FirstName + Iif(i.MiddleName IS NOT NULL, ' ' + i.MiddleName + ' ', ' ') + i.Surname AS [AName],
rn = ROW_NUMBER() OVER (PARTITION BY uc.CId, uc.[UId] ORDER BY uc.ModifiedAt)
FROM uc
INNER JOIN cteuag ON cteuag.CId = uc.CId
AND uc.IsDeleted = 0
INNER JOIN ui ON ui.[UId] = uc.[UId]
AND ui.IsDeleted = 0
INNER JOIN i ON i.PId = ui.IndividualId
),
ctel AS
(
SELECT
la.LId,
p.CId,
la.[UId],
rn = ROW_NUMBER() OVER (PARTITION BY la.LId ORDER BY la.DateUpdated DESC)
FROM la
INNER JOIN p ON p.Id = la.PId
AND p.IsDeleted = 0
AND la.IsDeleted = 0
AND la.[UId] IS NOT NULL
INNER JOIN l ON la.LId = l.Id
AND l.IsDeleted = 0
)
SELECT
c.Id AS CId,
c.[Name] AS CName,
u.Id AS AId,
cteuc.AName AS AName,
ctel.LId AS LId,
qh.Id AS QhId,
q.Id AS QId,
q.IsTrue AS isTrue,
p.Id AS PId,
p.[Name] AS PName,
qi.FinalCalculation AS Calculation
INTO #FilteredData
FROM c
INNER JOIN cteuc ON cteuc.CId = c.Id
AND cteuc.Rn = 1
AND c.IsDeleted = 0
LEFT OUTER JOIN u ON u.Id = Iif(cteuc.AuthorIsatIonGroupId = 1, #UId, cteuc.[UId])
AND u.IsDeleted = 0
LEFT OUTER JOIN ctel ON ctel.CId = c.Id
AND ctel.Rn = 1
AND ctel.[UId] = u.Id
LEFT OUTER JOIN
(
la
INNER JOIN qla ON qla.LeadActivityId = la.Id
AND la.IsDeleted = 0
AND la.ActivityTypeId = 4
INNER JOIN qh ON qla.QhId = qh.Id
AND qh.IsDeleted = 0
AND qh.IsReRated = 0
LEFT OUTER JOIN
(
q
INNER JOIN p ON p.Id = q.PId
AND q.IsDeleted = 0
AND p.IsDeleted = 0
) ON q.QhId = qh.Id) ON la.[UId] = u.Id
AND la.LId = ctel.LId
LEFT OUTER JOIN
(
SELECT
qi1.QId,
SUM(Iif(qi1.Calculation = 0, 0, qi1.Calculation + qi1.Extra)) AS FinalCalculation
FROM qi
WHERE qi1.IsDeleted = 0
GROUP BY QId
) AS qi ON qi.QId = q.Id
SELECT * FROM #FilteredData
so I know it is not the comma delimited values used as filters, or the leading wild cards.
So it turns out it runs fine on another laptop, which means it was something to do with my laptop. Regardless, looking at the comments, this query could use a lot of refinement

How to write one CASE function two THEN method at the same time END AS Two NEW column depend on THEN action

SELECT Emp.IntegrationFieldOne AS LocationCode, Emp.EmployeeId,
Emp.FirstName + ' '+ Emp.LastName as 'EmployeeName',
CASE WHEN ( (ORSet.Rate) =1.5 ) THEN
Sum(OT.Minutes)
END AS '1.5HRSMinutes',
CASE WHEN( ORSet.Rate =2 ) THEN
Sum(OT.Minutes)
END AS '2HRSMinutes'
FROM [CemexDB_CP_Test].[TimeAttendance].[OvertimeTransaction] OT
INNER JOIN [HumanResource].[Employee] Emp ON OT.EmployeeId = Emp.EmployeeId
INNER JOIN [CemexDB_CP_Test].[TimeAttendance].[OvertimeRateSettingDetail]
ORSet ON ORSet.OvertimeRateSettingId= OT.OvertimeType
GROUP BY Emp.EmployeeId,Emp.FirstName,Emp.LastName,Emp.IntegrationFieldOne,ORSet.Rate[!
This is Output picture click it]1
This is the out put but i want same row depend same id. but here each id has 2
row how to handle it
I think you want conditional aggregation:
SELECT Emp.IntegrationFieldOne AS LocationCode, Emp.EmployeeId,
Emp.FirstName + ' '+ Emp.LastName as EmployeeName,
SUM(CASE WHEN ORSet.Rate = 1.5 THEN OT.Minutes END) AS [1.5HRSMinutes],
SUM(CASE WHEN ORSet.Rate = 2 THEN OT.Minutes END) AS [2HRSMinutes]
FROM [CemexDB_CP_Test].[TimeAttendance].[OvertimeTransaction] OT INNER JOIN
[HumanResource].[Employee] Emp
ON OT.EmployeeId = Emp.EmployeeId INNER JOIN
[CemexDB_CP_Test].[TimeAttendance].[OvertimeRateSettingDetail]
ORSet
ON ORSet.OvertimeRateSettingId= OT.OvertimeType
GROUP BY Emp.EmployeeId, Emp.FirstName, Emp.LastName, Emp.IntegrationFieldOne;

SQL how to cross reference two unrelated tables

I need to cross reference from these 2 tables and display only the matching contindex from the first table if the contindex from the other table matches. Below is an image of what i have. Also the code is pasted below.
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
Basically I need to show only the top table rows that match the bottom table contindex.
Sounds like the tables are related by contindex, no? Anyhow, copy and pasting your code and adding just a little bit extra should do the trick:
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
)
The additional code is the WHERE t.contindex IN (<yoursecondquery>) You could accomplish the same thing with an INNER JOIN too, but this is a quick-fix given that you already wrote out both queries seperately.
You can use an IN or EXISTS here.. You just need to alter the second query slightly to add a WHERE condition if you use 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) )