extracting certain part of string in SQL stored procedure - sql

I have this stored procedure at the moment. I would like to limit the String ChanceOfSuccess to only a the percentage like "40%". Right now the string reads something like this "40% - Thinking about it". What would be the best way to do this?
CREATE PROCEDURE [dbo].[procActivity_SelectbyOutstandingActivitiesNew]
AS
SELECT C.[Name] AS [Customer],
C.CustomerId AS [CustomerID],
E.FirstName + ' ' + E.Surname AS [Employee],
AT.[TypeName] AS [Activity Type],
A.[ActivityDate] AS ActivityDate,
A.NextActivityDate,
A.[ChanceOfSuccess] AS ChanceOfSuccess,
A.[Comments] AS Comments,
U.Surname + ' ' + U.FirstName AS [User],
E.EmployeeId,
A.ActivityId,
CONVERT(INT, SUBSTRING(A.ChanceOfSuccess, 0, CHARINDEX ('%',A.ChanceOfSuccess))) AS [Success Percentage],
A.[IsComplete]
FROM Customer C
INNER JOIN Activity A ON A.CustomerId = C.CustomerId
INNER JOIN Employee E ON E.EmployeeId = A.EmployeeId AND E.CustomerId = C.CustomerId
INNER JOIN [ActivityType] AT ON A.[ActivityTypeId] = AT.[ActivityTypeId]
INNER JOIN [User] U ON A.[UserId] = U.[UserId]
LEFT OUTER JOIN Activity A2 ON A.CustomerId = A2.CustomerId AND A.UserId = A2.UserId AND A2.ActivityDate > A.ActivityDate
WHERE C.[IsDeleted] = 0
AND A.NextActivityDate <= GETDATE()
AND E.IsDeleted = 0
AND A.IsDeleted = 0
AND (A2.ActivityId IS NULL OR A2.IsDeleted > 0)
AND CONVERT(INT, SUBSTRING(A.ChanceOfSuccess, 0, CHARINDEX ('%',A.ChanceOfSuccess))) < 100
ORDER BY A.NextActivityDate ASC, Customer, A.ActivityDate ASC, [Success Percentage] DESC
GO

Homework? you clearly didn't write the original query because it's already doing that work.
The line:
CONVERT(INT, SUBSTRING(A.ChanceOfSuccess, 0, CHARINDEX ('%',A.ChanceOfSuccess))) AS [Success Percentage],
Already does what you want and then converts it to an int, so remove the conversion and you should have what you want.
DECLARE #v VARCHAR(50) = '40% - Thinking about it'
SELECT #V, SUBSTRING(#V, 0, charindex('%', #V)+1)

Here are some surgestions to how to rewrite your code:
create view [v_OutstandingActivities]
AS
SELECT C.[Name] AS [Customer],
C.CustomerId AS [CustomerID],
E.FirstName + ' ' + E.Surname AS [Employee],
AT.[TypeName] AS [ActivityType],
A.[ActivityDate] AS ActivityDate,
A.NextActivityDate,
A.[ChanceOfSuccess] AS ChanceOfSuccess,
A.[Comments] AS Comments,
U.Surname + ' ' + U.FirstName AS [UserName],
E.EmployeeId,
A.ActivityId,
replace(A.ChanceOfSuccess, '%', '')+0 AS [SuccessPercentage],
A.[IsComplete]
FROM Customer C
INNER JOIN Activity A ON A.CustomerId = C.CustomerId
INNER JOIN Employee E ON E.EmployeeId = A.EmployeeId AND E.CustomerId = C.CustomerId
INNER JOIN [ActivityType] AT ON A.[ActivityTypeId] = AT.[ActivityTypeId]
INNER JOIN [User] U ON A.[UserId] = U.[UserId]
LEFT OUTER JOIN Activity A2 ON A.CustomerId = A2.CustomerId AND A.UserId = A2.UserId
AND A2.ActivityDate > A.ActivityDate AND (A2.IsDeleted > 0)
WHERE C.[IsDeleted] = 0
AND A.NextActivityDate <= GETDATE()
AND E.IsDeleted = 0
AND A.IsDeleted = 0
AND replace(A.ChanceOfSuccess, '%', '') < 100

Related

want to show a specific data, but somehow the data are duplicate by something

I want to show a specific data with a specific quantity of the data using SQL. On this case, its should be shown only 5 records, but it shown 10 records and they are the same data, I really don't know where the problem is. any body can help to solve this?
I've just tried sort out the code, by running each of them, but I think i found the problem on the section #TEMPAD
anyone can confirm my problem?
--IMAGE : https://imgur.com/a/xgX5hub
DECLARE #Month AS INT = 1
DECLARE #Year AS INT = 2019
DECLARE #EmployeeID AS VARCHAR(16) = '01113'
DECLARE #BranchID AS VARCHAR(16) = ''
DECLARE #DepartmentID AS VARCHAR(16) = ''
SELECT * INTO #TEMPJAMINAN FROM(
SELECT A.EmployeeID, SUM(B.Amount) AS JaminanPaid, SUM(A.Amount) AS TotalJaminan
FROM Loan A
INNER JOIN LoanDetail B ON A.LoanID = B.LoanID
WHERE A.EmployeeID = #EmployeeID AND IsPaid = 1 AND LoanTypeID = '017'
GROUP BY A.EmployeeID
)A
SELECT * INTO #TEMPKOPERASI FROM(
SELECT A.EmployeeID, SUM(B.Amount) AS KoperasiPaid, A.Amount AS TotalKoperasi
FROM Loan A
INNER JOIN LoanDetail B ON A.LoanID = B.LoanID
WHERE A.EmployeeID = #EmployeeID AND IsPaid = 1 AND LoanTypeID = '011' AND A.IsDeleted = 0 AND A.Paid = 1
GROUP BY A.EmployeeID, A.Amount
)A
SELECT *, 2 AS SEQ INTO #TEMPAD FROM(
SELECT A.EmployeeID, C.Name AS 'ADName', 'DEDUCTION' AS [Type], B.Amount
FROM Salary A
INNER JOIN SalaryDeduction B ON A.SalaryID = B.SalaryID
INNER JOIN Deduction C ON B.DeductionID = C.DeductionID
WHERE EmployeeID = #EmployeeID AND A.Month = #Month AND A.Year = #Year
UNION ALL
SELECT A.EmployeeID, C.Name AS 'ADName', 'ALLOWANCE' AS [Type], B.Amount
FROM Salary A
INNER JOIN SalaryAllowance B ON A.SalaryID = B.SalaryID
INNER JOIN Allowance C ON B.AllowanceID = C.AllowanceID
WHERE EmployeeID = #EmployeeID AND A.Month = #Month AND A.Year = #Year
UNION ALL
SELECT A.EmployeeID, E.Name AS 'ADName', 'DEDUCTION' AS [Type], SUM(F.Amount) AS Amount
FROM Employee A
INNER JOIN Branch B ON A.BranchID = B.BranchID
INNER JOIN Department C ON A.DepartmentID = C.DepartmentID
INNER JOIN Loan D ON A.EmployeeID = D.EmployeeID
INNER JOIN LoanDetail F ON D.LoanID = F.LoanID AND (MONTH(F.TransDate) = #Month AND YEAR(F.TransDate) = #Year AND IsPaid = 1)
INNER JOIN LoanType E ON D.LoanTypeID = E.LoanTypeID
WHERE A.IsDeleted = 0 AND A.EndWorking IS NULL AND A.EmployeeID = #EmployeeID
GROUP BY A.EmployeeID, E.Name
)A
SELECT
UPPER(C.Name) AS CompanyName,
C.Address1 AS [Address1],
C.Address2 AS [Address1],
#Year AS [Year],
UPPER(CAST(DATENAME(MONTH,DATEADD(MONTH,#Month,-1)) AS VARCHAR(20))) AS [Month],
B.NIK AS NIKKaryawan,
UPPER(B.Name) AS NamaKaryawan,
UPPER(D.Name) AS Title,
UPPER(E.Name) AS Department,
A.HKS AS TotalHKS,
A.HKA AS TotalHKA,
B.AccountBank AS RekeningKaryawan,
B.BankName AS BankKaryawan,
F.JaminanPaid,
F.TotalJaminan,
G.KoperasiPaid,
G.TotalKoperasi,
A.Netto AS TotalGaji,
VE.ADName,
VE.Type,
VE.Amount,
2 AS SEQ
FROM Salary A
INNER JOIN Employee B ON A.EmployeeID = B.EmployeeID
INNER JOIN Company C ON B.CompanyID = C.CompanyID
INNER JOIN Title D ON B.TitleID = D.TitleID
INNER JOIN Department E ON B.DepartmentID = E.DepartmentID
LEFT JOIN #TEMPJAMINAN F ON A.EmployeeID = F.EmployeeID
LEFT JOIN #TEMPKOPERASI G ON A.EmployeeID = G.EmployeeID
LEFT JOIN #TEMPAD VE ON A.EmployeeID = VE.EmployeeID
WHERE A.EmployeeID = #EmployeeID AND A.IsDeleted = 0
UNION ALL
SELECT
UPPER(C.Name) AS CompanyName,
C.Address1 AS [Address1],
C.Address2 AS [Address1],
#Year AS [Year],
UPPER(CAST(DATENAME(MONTH,DATEADD(MONTH,#Month,-1)) AS VARCHAR(20))) AS [Month],
B.NIK AS NIKKaryawan,
UPPER(B.Name) AS NamaKaryawan,
UPPER(D.Name) AS Title,
UPPER(E.Name) AS Department,
A.HKS AS TotalHKS,
A.HKA AS TotalHKA,
B.AccountBank AS RekeningKaryawan,
B.BankName AS BankKaryawan,
F.JaminanPaid,
F.TotalJaminan,
G.KoperasiPaid,
G.TotalKoperasi,
A.Netto AS TotalGaji,
'GAJI POKOK',
'ALLOWANCE',
B.BasicSalary,
1 AS SEQ
FROM Salary A
INNER JOIN Employee B ON A.EmployeeID = B.EmployeeID
INNER JOIN Company C ON B.CompanyID = C.CompanyID
INNER JOIN Title D ON B.TitleID = D.TitleID
INNER JOIN Department E ON B.DepartmentID = E.DepartmentID
LEFT JOIN #TEMPJAMINAN F ON A.EmployeeID = F.EmployeeID
LEFT JOIN #TEMPKOPERASI G ON A.EmployeeID = G.EmployeeID
WHERE A.EmployeeID = #EmployeeID AND A.IsDeleted = 0
AND (B.DepartmentID = #DepartmentID OR #DepartmentID = '')
AND (B.BranchID = #BranchID OR #BranchID = '')
GROUP BY
DROP TABLE #TEMPAD
DROP TABLE #TEMPJAMINAN
DROP TABLE #TEMPKOPERASI
I expect the output of 5 data instead of 10

Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int

I have a query that is getting some that is comparing a uniqueidentifier in the table and its a strange one.
SELECT * FROM vw_ryzex_CustomerAssets where BillToId='51ee47d2-eb97-4b12-8865-dab9a7f15a46'
So when i run this query i get the following error
Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int.
But when i select only the top 1000 i get the result and no error occurrs I tried Casting and converting checking nulls everything i could i tried following queries but did not work
SELECT * FROM vw_ryzex_CustomerAssets_V2 where CAST(BillToId as nvarchar(200))=Cast('51ee47d2-eb97-4b12-8865-dab9a7f15a46' as nvarchar(200))
SELECT * FROM vw_ryzex_CustomerAssets where (Case BillToId
when '00000000-0000-0000-0000-000000000000' Then NEWID()
ELSE BillToId
END) = '51ee47d2-eb97-4b12-8865-dab9a7f15a46'
Can anyone help me on this please..?
This is the view definition
ALTER VIEW [dbo].[vw_ryzex_CustomerAssets_V2] AS SELECT a.Id,
'~/Reports/BillToAssetDetails.aspx?btid='
+ CONVERT(VARCHAR(256), a.BillToId)
+ '&vidx=1&caid='
+ CONVERT(VARCHAR(256), a.Id) AS URL,
'~/Reports/BillToAssets.aspx?btid='
+ CONVERT(VARCHAR(256), a.BillToId)
+ '&vidx=1&caid='
+ CONVERT(VARCHAR(256), a.Id) AS EditUrl,
LEFT(a.PartDescription, 50) AS PartDescription,-- EKL:03042009
a.Quantity,
a.SerialNumber,
/* CASE ISNULL(s.Name,'') WHEN '' THEN a.Location ELSE s.Name + '(' + s.ErpId + ')
'+ a.Location END AS Location, */
a.Location,
s.NAME + '(' + s.ErpId + ')' AS SiteName,
--a.OrderId,
o.OrderGroupId AS OrderId,
a.OrderErpId,
a.OrderExt,
a.OrderLine,
a.DateCreated,
a.DateModified,
Isnull(ru.DisplayName, '') AS ModifiedBy,
a.BillToId,
a.PartNo,
b.NAME AS BillToName,
b.Description AS BillToDescription,
b.ErpId AS BillToErpId,
b.DateCreated AS BillToDateCreated,
b.DateModified AS BillToDateModified,
b.ModifiedBy AS BillToModifiedBy,
a.ProductId,
--p.ProductPartNo,
--p.ProductModel,
--p.ProductDescription as ProductDescription,
--p.ProductDateCreated,
--p.ProductDateModified,
--p.ProductModifiedBy,
Isnull(ol.UnitPrice, '0') AS UnitPrice,
ol.SalesTax,
Isnull(ol.TotalPrice, '0') AS TotalPrice,
ol.OrderErpId AS OrderLineId,
Isnull(ol.QuantityOrdered, '0') AS QuantityOrdered,
Isnull(ol.QuantityShipped, '0') AS QuantityShipped,
-- o.Created AS OrderDate,
Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.Created) AS OrderDate,
-- o.ShippedDate AS ShipDate,
Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.ShippedDate) AS ShipDate,
o.SalesPersonName AS SalesPersonDisplayName,
o.BillingCurrency AS Currency,
dbo.vw_PurchaseOrderPayments.PurchaseOrderPaymentNumber AS CustPo,
a.AssetNumber,
a.CustomerReference,
a.ModelNumber,
a.CustomField1Value AS xCust1,
a.CustomField2Value AS xCust2,
s.Id AS ShipToId,
s.AddressLine1 AS Address1,
s.AddressLine2 AS Address2,
s.AddressLine3 AS Address3,
s.City,
s.Country,
s.[State],
s.ZipCode AS Zip
FROM dbo.vw_PurchaseOrderPayments
RIGHT OUTER JOIN dbo.vw_PurchaseOrders AS o
ON dbo.vw_PurchaseOrderPayments.OrderFormId = o.OrderFormId -- EKL:03042009 chg from OrderGroupId to OrderFormId
RIGHT OUTER JOIN dbo.ryzex_CustomerAsset AS a
INNER JOIN dbo.ryzex_BillTo AS b WITH (NOLOCK)
ON a.BillToId = b.Id
AND Isnull(a.Inactive, 0) = 0
LEFT OUTER JOIN dbo.ryzex_ShipTo AS s WITH (NOLOCK)
ON a.ShipToId = s.Id
AND b.Id = s.BillToId
LEFT OUTER JOIN dbo.ryzex_Product AS p WITH (NOLOCK)
ON a.PartNo = p.ProductPartNo
LEFT OUTER JOIN dbo.vw_OrderLines AS ol
ON a.OrderErpId = ol.OrderErpId
AND a.OrderLine = ol.LineNumber
ON o.OrderErpNumber = a.OrderErpId
AND o.OrderExtensionNumber = a.OrderExt
LEFT OUTER JOIN dbo.ryzex_Users AS ru WITH (NOLOCK)
ON a.ModifiedBy = ru.Id
The BillToId that is coming from ryzex_CustomerAsset tbl is a not null uniqueidentifier

Stored procedure for a select statement

I got a select statement. I want to add a join to this select statement and the join which I want to add is at the bottom of this code. why am I unable to add one more left outer join for this select statement? The join which I want to add is at the bottom. I also need to write a stored procedure for the entire select statement:
SELECT
FactId, UserType,
wr.WorkRequestId, wr.XerisUserKey,
xu.CsuserUserID UserId,
u.fname UserFName, u.lname UserLName,
b.PatientId, p.firstname PatFName, p.lastname PatLName,
GroupId, HospiceGroupKey GroupKey, WR.ContactKey,
C.ContactId, C.FirstName, C.LastName,
Convert(datetime, (Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay )) Start_dtm,
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay )) End_dtm,
DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay)),
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay ))) WRDuration,
(Convert(Decimal(18, 3), DATEDIFF(s, Convert(datetime,(Convert(varchar, SD.Date, 101) + ' ' + ST.TimeOfDay )),
Convert(datetime, (Convert(varchar, CD.Date, 101) + ' ' + CT.TimeOfDay ))))) *
(Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration,
CallBackNumber, WorkRequestType,
B.LineItemCount, ArchiveLocation, Processed,
ArchiveQueueType, TQA, Exclude, CallId
FROM
bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN
bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN
bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN
bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN
cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN
bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN
bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN
bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN
bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN
bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
WHERE
CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
This is the join I want to add to this select statement
left outer join
ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy (nolock) h on b.groupid = h.group_id
You are not allowed to call a table valued function remotely (ie across servers).
There is a workaround here:
Workaround for calling table-valued function remotely in SQL Server has even more issues
And more info here:
http://social.msdn.microsoft.com/Forums/en-US/1f0d2885-faa2-496a-b010-edc441260138/remote-tablevalued-function-calls-are-not-allowed?forum=transactsql

Order By Case multiple fields

The code below (and numerous codes like it) continues to return blanks.
Basically, if LaborCode = '01 - SC' then it should sort by JobSite, LaborCode, and Schedule (the exact date)
If it's NOT 01 - SC, it should sort by JobSite, LaborCode, and DayNo (the day of the week)
Select Distinct Agreements.AgrmntID, Agreements.Description, Agreements.Status,
JobSites.SiteName, JobSites.Address2, JobSites.City, Customers.CustName,
Customers.CompanyName, LaborCodeTypes.RepairCode As LaborCode, Schedule = Case
LaborCodeTypes.RepairCode
When '01 - SC' Then Left(Convert(varchar,AgreementSchedules.SchedDate,110),
10) Else DateName(dw, AgreementSchedules.SchedDate)
End, Employees1.EmpName As Vendor, Employees.EmpName As [Area Manager],
DatePart(dw, AgreementSchedules.SchedDate) As DayNo
From Agreements Inner Join
Customers On Agreements.CustID = Customers.CustID Inner Join
AgreementSchedules On Agreements.AgrmntID = AgreementSchedules.AgrmntID
Inner Join
JobSites On Agreements.CustSiteID = JobSites.CustSiteID Left Outer Join
LaborCodeTypes On AgreementSchedules.RepairID = LaborCodeTypes.RepairID
Left Outer Join
Employees On AgreementSchedules.FormanEmpID = Employees.EmployeeID Left Join
WorkOrderSchedules On WorkOrderSchedules.ScheduleID =
AgreementSchedules.ScheduleID And AgreementSchedules.ScheduleID =
WorkOrderSchedules.ScheduleID Left Join
WorkOrderScheduleTechs On WorkOrderSchedules.ScheduleID =
WorkOrderScheduleTechs.ScheduleID Left Join
Employees Employees1 On WorkOrderScheduleTechs.EmployeeID =
Employees1.EmployeeID
Where Agreements.Status = 2 And LaborCodeTypes.RepairCode <> 'Vendor Bill' And
Month(AgreementSchedules.SchedDate) = Month(GetDate())
Order By Case
When [LaborCodeTypes.RepairCode] In ('01 - SC') Then JobSites.SiteName +
LaborCodeTypes.RepairCode + Schedule
Else JobSites.SiteName + LaborCodeTypes.RepairCode + DayNo End
Thank you for your help!!
Try this:
ORDER BY JobSites.SiteName,
LaborCodeTypes.RepairCode,
CASE WHEN LaborCodeTypes.RepairCode IN ('01 - SC') THEN Schedule ELSE DayNo END
Okay, in SQL Server:
CREATE PROCEDURE dbo.Agreements_GetList
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
a.AgrmntID,
a.Description,
a.Status,
js.SiteName,
js.Address2,
js.City,
c.CustName,
c.CompanyName,
LaborCode = lct.RepairCode,
Schedule = CASE lct.RepairCode
WHEN '01 - SC' THEN CONVERT(CHAR(10), aSch.SchedDate, 110)
--------------------^^^ much better than LEFT and not specifying length
ELSE DATENAME(WEEKDAY, aSch.SchedDate) END,
Vendor = e2.EmpName,
[Area Manager] = e1.EmpName,
DayNo = CONVERT(CHAR(1), DATEPART(WEEKDAY, aSch.SchedDate))
--------^^^ this convert is important
FROM dbo.Agreements AS a
INNER JOIN dbo.Customers AS c
ON a.CustID = c.CustID
INNER JOIN dbo.AgreementSchedules AS aSch
ON a.AgrmntID = aSch.AgrmntID
INNER JOIN dbo.JobSites AS js
ON a.CustSiteID = js.CustSiteID
LEFT OUTER JOIN dbo.LaborCodeTypes AS lct
ON aSch.RepairID = lct.RepairID
LEFT OUTER JOIN dbo.Employees AS e1
ON aSch.FormanEmpID = e1.EmployeeID
LEFT OUTER JOIN dbo.WorkOrderSchedules AS w
ON w.ScheduleID = aSch.ScheduleID
LEFT OUTER JOIN dbo.WorkOrderScheduleTechs AS wt
ON w.ScheduleID = wt.ScheduleID
LEFT OUTER JOIN dbo.Employees AS e2
ON wt.EmployeeID = e2.EmployeeID
WHERE
a.Status = 2
AND lct.RepairCode <> 'Vendor Bill'
AND aSch.SchedDate >= DATEADD(MONTH, 0, DATEDIFF(MONTH, 0, GETDATE()))
AND aSch.SchedDate < DATEADD(MONTH, 1, DATEDIFF(MONTH, 0, GETDATE()))
ORDER BY
js.SiteName,
lct.RepairCode,
CASE WHEN lct.RepairCode = '01 - SC'
THEN js.SiteName ELSE DayNo END;
END
GO
Now I have absolutely no knowledge of your application, so you will have to figure out how to call a stored procedure from it instead of embedding SQL.

New to SQL how do I get both contactsid's from contacts and tasks using a left outter join?

I wrote this report to display how long it takes a user to finish their first task. currently it will only display contacts that have tasks. I need it to display both contacts with and without tasks any ideas?
SELECT c.MarketSource AS [Market Source],
Coalesce(u.FirstName + ' ', ' ') + Coalesce(u.LastName, ' ') AS [Producer],
Coalesce(c.FirstName + ' ', ' ') + Coalesce(c.MiddleName + ' ', ' ') + Coalesce(c.LastName, ' ') AS [Lead Name],
t.TaskType AS [Task],
Coalesce (t.workflow_resultchosen_label, t.result, ' ') AS [Task Result],
Dateadd(HOUR, #utcoffset, c.createdon) AS [Received On],
Dateadd(HOUR, #utcoffset, ( MIN (t.completed) )) AS [Completed],
(SELECT COUNT(*)
FROM Quotes q WITH (NOLOCK)
WHERE SaleID IS NULL
AND c.ContactID = q.ContactID) AS [Pending Quotes],
(SELECT COUNT(*)
FROM Sales s WITH (NOLOCK)
WHERE s.Client_ID = c.ContactID) AS [Total Sales]
FROM Tasks t WITH (NOLOCK)
LEFT JOIN Users U WITH (NOLOCK)
ON u.UserID = t.UserID
LEFT JOIN Contacts C WITH (NOLOCK)
ON c.ContactID = t.TargetID
WHERE iLeadPartnerID IS NOT NULL
AND ( c.CreatedOn BETWEEN #startDate AND #endDate )
AND MarketSource IS NOT NULL
AND c.WorkgroupId = #workgroupID
AND Len(c.MarketSource) > 0
AND t.TaskType <> '[=] Auto Email'
GROUP BY c.MarketSource,
u.LastName,
u.FirstName,
c.ContactId,
c.LastName,
c.FirstName,
c.MiddleName,
c.CreatedOn,
t.TaskType,
t.Result,
t.Workflow_ResultChosen_Label
ORDER BY c.LastName,
c.MiddleName,
c.FirstName
You need to use a Left Join from Contacts to Tasks (i.e., show all contacts and any matching Tasks). In addition, you need to move the criteria t.TaskType <> '[=] Auto Email' to the ON clause or change the Where clause filter to be:
(t.TaskType <> '[=] Auto Email' Or t.TaskType Is Null).
Otherwise, your Left Join to Tasks will effectively become an Inner Join.
SELECT c.MarketSource AS [Market Source]
, Coalesce(u.FirstName + ' ', ' ') + Coalesce(u.LastName, ' ') AS [Producer]
, Coalesce(c.FirstName + ' ', ' ') + Coalesce(c.MiddleName + ' ', ' ') + Coalesce(c.LastName, ' ') AS [Lead Name]
, t.TaskType AS [Task], Coalesce (t.workflow_resultchosen_label, t.result, ' ') AS [Task Result]
, Dateadd(HOUR, #utcoffset, c.createdon) AS [Received On]
, Dateadd(HOUR, #utcoffset, ( MIN (t.completed) )) AS [Completed]
, (SELECT COUNT() FROM Quotes q WITH (NOLOCK) WHERE SaleID IS NULL AND c.ContactID = q.ContactID) AS [Pending Quotes]
, (SELECT COUNT() FROM Sales s WITH (NOLOCK) WHERE s.Client_ID = c.ContactID) AS [Total Sales]
From Contacts As C WITH (NOLOCK)
Left Join Tasks t WITH (NOLOCK)
On t.TargetID = C.ContactId
And t.TaskType <> '[=] Auto Email'
LEFT JOIN Users U WITH (NOLOCK)
ON u.UserID = t.UserID
WHERE iLeadPartnerID IS NOT NULL
AND ( c.CreatedOn BETWEEN #startDate AND #endDate )
AND MarketSource IS NOT NULL
AND c.WorkgroupId = #workgroupID
AND Len(c.MarketSource) > 0
GROUP BY c.MarketSource, u.LastName, u.FirstName, c.ContactId
, c.LastName, c.FirstName, c.MiddleName, c.CreatedOn, t.TaskType
, t.Result, t.Workflow_ResultChosen_Label
ORDER BY c.LastName, c.MiddleName, c.FirstName