Joining multiple tables results in duplicate rows - sql

There are tow tables (Customer & Feedback) that have different information. The following query is almost correct, except that it results in duplicate rows. I only need unique rows as par customerId and NO for null value.
I tried the GROUP BY clause at the end but it gives error.
Select C.CustomerId,
C.FirstName,
C.LastName,
(SELECT CAST(CASE WHEN F.Id != null or F.Type = 'Query'
THEN 'YES' ELSE 'NO' END AS NVARCHAR(50))) as Query,
(SELECT CAST(CASE WHEN F.Id != null or F.Type = 'Feedback'
THEN 'YES' ELSE 'NO' END AS NVARCHAR(50))) as Feedback
FROM Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
Select * from Customer
Select * from Feedback
As Result I want to display only single row by customerId and to join the feedback table data like below...

You May Try either of the Below
SELECT
C.*,
Query = CASE WHEN PVT.Query IS NOT NULL THEN 'Yes' ELSE 'No' END,
Feedback = CASE WHEN PVT.Feedback IS NOT NULL THEN 'Yes' ELSE 'No' END
FROM Customer C
LEFT JOIN FeedBack
PIVOT
(
MAX(Id)
FOR
[Type] IN
(
[Query],[Feedback]
)
)Pvt
ON PVT.CustomerId = c.CustomerId
or Simply
SELECT
C.*,
Query = CASE WHEN EXISTS(SELECT 1 FROM FeedBack WHERE CustomerId = C.CustomerId and [Type]='Query') THEN 'Yes' ELSE 'No' END,
Feedback = CASE WHEN EXISTS(SELECT 1 FROM FeedBack WHERE CustomerId = C.CustomerId and [Type]='Feedback') THEN 'Yes' ELSE 'No' END
FROM Customer C
To Make it more Dynamic ou may Try this
DECLARE #SQL VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY [Type] ORDER BY [Type]),
QRY = LTRIM(RTRIM([Type]))+' = CASE WHEN EXISTS(SELECT 1 FROM FeedBack WHERE CustomerId = C.CustomerId and [Type]='''+LTRIM(RTRIM([Type]))+''') THEN ''Yes'' ELSE ''No'' END'
FROM FeedBack
)
SELECT
#SQL = 'SELECT
C.*'
+SUBSTRING(','+L.List,1,LEN(L.List)-1)
+' FROM Customer C'
FROM
(
SELECT
QRY + ', ' [text()]
FROM CTE
WHERE RN = 1
FOR XML PATH('')
)L(List)
EXEC(#SQL)
Please Refer this Sqlfiddle for detailed example

Select C.CustomerId,
C.FirstName,
C.LastName,
sum(case when F.Type = 'Query' then 1 else 0 end) > 0 as Query,
sum(case when F.Type = 'Feedback' then 1 else 0 end) > 0 as Feedback
FROM Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
GROUP BY C.CustomerId, C.FirstName, C.LastName

use case when
Select C.CustomerId,
C.FirstName,
C.LastName,
case when sum(case when F.Type = 'Query' then 1 else 0 end) > 0 then 'Yes' else 'NO' end as Query,
case when sum(case when F.Type = 'Feedback' then 1 else 0 end) > 0 then 'Yes' else 'NO' End as Feedback
FROM Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
GROUP BY C.CustomerId, C.FirstName, C.LastName

Try below query using subquery:
select *,case when query=1 then 'Yes' else 'No' end as query,
case when feedback=1 then 'Yes' else 'No' end as feedbackfrom
(select CustomerId, firstname,lastname,
sum(CASE WHEN Type = 'Query'
THEN 1 ELSE 0 END) as Query,
sum(CASE WHEN Type = 'Feedback'
THEN 1 ELSE 0 END) as Feedback from Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
group by CustomerId, firstname,lastname)a

Try this:
select c.CustomerId,
c.FirstName,
c.LastName,
case when q.CustomerId is null then 'NO' else 'YES' end Query,
case when f.CustomerId is null then 'NO' else 'YES' end Feedback,
from Customers c
left join (select customerId from Feedback where Type = 'Query' ) q on c.CustomerId = q.CustomerId
left join (select customerId from Feedback where Type = 'Feedback' ) f on c.CustomerId = q.CustomerId

Related

CASE statement in the ORDER BY CLAUSE

SQL SERVER
I'm attempting to sort records in my ORDER BY clause in an exact manner. So the records should be sorted in the following manner. I think my issue might be the CASE STATEMENT syntax, but I can't seem to find anything telling me that it's wrong, other than the code not running.
od.Status
Firm,
In Process,
Released,
Everything Else
I believed I could assign each type of record a number, and then sort those numbers.
The code below gives me "ORDER BY items must appear in the select list if SELECT DISTINCT is specified"
SELECT DISTINCT
oh.Order_Number AS Order_Number,
oh.Status AS Order_Status,
oh.Customer_Name AS Customer_Name,
vsc.Salesman_Name AS Salesman_Name,
vsc.Email_Address AS Email_Address,
od.Work_Code AS Work_Code,
od.Product_Code AS Product_Code,
CONVERT(char(10),od.Projected_Ship_Date,101) AS Projected_Ship_Date,
CONVERT(char(10),od.Due_Date,101) AS OD_Due_Date,
format(oh.Gross_Amount, '$#,##0.##') AS Gross_Amount,
DATEDIFF(DAY,oh.Order_Date,'{%Current Date%}') AS DIP,
od.Part_Number AS Part_Number,
od.Status AS Status,
CAST(qd.Delivery_Notes AS NVARCHAR(MAX)) AS Delivery_Notes
FROM
dbo.Order_Header oh LEFT OUTER JOIN dbo.Commission_Distribution cd ON oh.Order_Header_ID = cd.Order_Header_ID LEFT OUTER JOIN
dbo.vSalesman_Code vsc ON cd.Salesman_Code = vsc.Salesman_Code JOIN
dbo.Order_Detail od ON od.Order_Header_ID = oh.Order_Header_ID JOIN
dbo.Quotation_Detail qd ON od.Quotation_Detail_ID = qd.Quotation_Detail_ID JOIN
dbo.Quotation_Header qh ON qd.Quotation_Header_ID = qh.Quotation_Header_ID
WHERE
oh.Status = 'Open' AND
cd.Company_Code = 'AIN' AND
oh.Customer_Name NOT IN ( 'A.I. Innovations' , 'AI PROPERTIES Fortville LLC' , 'AI-IN Intercompany' , 'AI-NC Intercompany' ) AND
od.Status <> 'Closed' AND
LEFT(od.Part_Number, 3) <> 'MTS' AND
vsc.Salesman_Name NOT IN ( 'House' , 'House Accounts' ) AND
od.Status <> 'Hold' AND
od.Product_Code NOT LIKE '%PROCES%' AND
od.Product_Code NOT LIKE '%VISTA WARRANT%'
ORDER BY
CASE
WHEN od.Status = 'Firm' THEN 1
WHEN od.Status = 'In Process' THEN 2
WHEN od.Status = 'Released' THEN 3
ELSE 4
END,
vsc.Email_Address ASC,
CONVERT(char(10),od.Projected_Ship_Date,101) ASC
Any help on this would be appreciated. I haven't been able to find very much on this issue. Most issues I've found want to sort one set DESC, and another set ASC, but not in a particular order.
Thanks
Just updated your query:
SELECT DISTINCT
oh.Order_Number AS Order_Number,
oh.Status AS Order_Status,
oh.Customer_Name AS Customer_Name,
vsc.Salesman_Name AS Salesman_Name,
vsc.Email_Address AS Email_Address,
od.Work_Code AS Work_Code,
od.Product_Code AS Product_Code,
CONVERT(char(10),od.Projected_Ship_Date,101) AS Projected_Ship_Date,
CONVERT(char(10),od.Due_Date,101) AS OD_Due_Date,
format(oh.Gross_Amount, '$#,##0.##') AS Gross_Amount,
DATEDIFF(DAY,oh.Order_Date,'{%Current Date%}') AS DIP,
od.Part_Number AS Part_Number,
od.Status AS Status,
CAST(qd.Delivery_Notes AS NVARCHAR(MAX)) AS Delivery_Notes,
CASE
WHEN od.Status = 'Firm' THEN 1
WHEN od.Status = 'In Process' THEN 2
WHEN od.Status = 'Released' THEN 3
ELSE 4
END As StatusOrderId
FROM
dbo.Order_Header oh LEFT OUTER JOIN dbo.Commission_Distribution cd ON
oh.Order_Header_ID = cd.Order_Header_ID LEFT OUTER JOIN
dbo.vSalesman_Code vsc ON cd.Salesman_Code = vsc.Salesman_Code JOIN
dbo.Order_Detail od ON od.Order_Header_ID = oh.Order_Header_ID JOIN
dbo.Quotation_Detail qd ON od.Quotation_Detail_ID = qd.Quotation_Detail_ID JOIN
dbo.Quotation_Header qh ON qd.Quotation_Header_ID = qh.Quotation_Header_ID
WHERE
oh.Status = 'Open' AND
cd.Company_Code = 'AIN' AND
oh.Customer_Name NOT IN ( 'A.I. Innovations' , 'AI PROPERTIES Fortville LLC' , 'AI-IN Intercompany' , 'AI-NC Intercompany' ) AND
od.Status <> 'Closed' AND
LEFT(od.Part_Number, 3) <> 'MTS' AND
vsc.Salesman_Name NOT IN ( 'House' , 'House Accounts' ) AND
od.Status <> 'Hold' AND
od.Product_Code NOT LIKE '%PROCES%' AND
od.Product_Code NOT LIKE '%VISTA WARRANT%'
ORDER BY
CASE
WHEN od.Status = 'Firm' THEN 1
WHEN od.Status = 'In Process' THEN 2
WHEN od.Status = 'Released' THEN 3
ELSE 4
END,
vsc.Email_Address ASC,
CONVERT(char(10),od.Projected_Ship_Date,101) ASC
The problem is that the "case" statement in your order by must actually appear as a column in the select statement because you are doing a select distinct. Here is an example, the first query is invalid, the second works
select distinct
tableName = t.name
from sys.tables t
order by case
when t.name like '%something%' then 1
else 2
end;
select distinct
orderingColumn = case
when t.name like '%something%' then 1
else 2
end,
tableName = t.name
from sys.tables t
order by case
when t.name like '%something%' then 1
else 2
end
The problem here is that the orderingColumn will be returned by the select statement, and it seems like you don't want that, but that's easily fixed by a CTE or subquery:
with MyQuery as
(
select distinct
orderingColumn = case
when t.name like '%something%' then 1
else 2
end,
tableName = t.name
from sys.tables t
)
select tableName from MyQuery order by orderingColumn;

Group by clause not returning the desired result

I have the following query that will pull the status of the courses enrolled for each user. I need to display a single record for that user that will represent the overall status of the courses. As you can see in the query below, it uses case statement to decide the prioritisation of the status. I have tried to use a group by clause but it still shows all the courses in the resultset. Could someone let me know what am I doing wrong in the query
DECLARE #Rep1 INT;
SET #Rep1 = 13119;
SELECT
cr.[CourseID]
, cr.[UserID]
,u.[Code]
,u.[DisplayName]
,t.[Name]
,cr.[CourseResultStatusID] AS [CourseResultStatusID]
,case
when min(case when crs.[Description] = 'Complete' then 1 else 0 end) = 1
then 'Complete'
when max(case when crs.[Description] = 'Fail' then 1 else 0 end) = 1
then 'Fail'
when max(case when crs.[Description] = 'Expired' then 1 else 0 end) = 1
then 'Expired'
when max(case when crs.[Description] = 'In Progress' then 1 else 0 end) = 1
then 'In Progress'
end as [CourseResultStatusDescription]
,c.[PointsRequired]
,cr.[ExpiryDateTime]
FROM [training].[CourseResult] cr
INNER JOIN [training].[Course] c
ON cr.[CourseID] = c.[ID] and c.[IsOptional] = 0 -- and cr.ExpiryDateTime > GetDate() and cr.ExpiryDateTime <= dateadd(dd,30,getdate())
INNER JOIN [training].[CourseResultStatus] crs
ON cr.[CourseResultStatusID] = crs.[ID]
INNER JOIN org.RepresentativeTierHistory rth on rth.RepresentativeID = cr.[UserID] and GetDate() between rth.StartDate and rth.EndDate
INNER JOIN org.tier t on t.ID = rth.TierID
LEFT JOIN [org].[User] u
ON u.[ID] = cr.[UserID]
WHERE cr.[UserID] IN (
SELECT hd.DescendantId FROM org.HierarchyDescendant hd WHERE hd.RepresentativeId = #Rep1 UNION ALL SELECT #Rep1 -- for management exchange info
)
group by cr.[CourseID], cr.[UserID], u.[Code], u.[DisplayName], t.[Name], [CourseResultStatusID],c.[PointsRequired],cr.[ExpiryDateTime]
The result of the query is below. As you can see there are 24 records. It is currently showing all the 6 courses per user. It should ideally only only 4 records.
REsultset that I am looking for

How to sum up the cursor value and store the value in another select statement in the same procedure?

I have two tables, one is general table and another is loan table.
General table includes id and name and id is not repeating.
Loan table includes id and loan amount. In loan table, the id may be repeating as one customer can have multiple loans.
Idea is to create a procedure which will join this both the table on the basis of id and display the final table with id, name and sum of all loans for that particular id (must sum up the value of common id's and store in single column) with the help of cursor.
Can only use procedure and cursor.
If it can be solved without cursor, then please provide the alternate solution.
I am using below query for the same, but unfortunately the end result displays the id multiple times:
SELECT
A.bpm_referenceno,
CASE WHEN B.loanbookingbranch='--Select--' or B.loanbookingbranch='null' THEN '' ELSE B.loanbookingbranch END,
CASE WHEN A.branch='' OR A.branch IS NULL OR A.branch='null' THEN '' ELSE A.branch END,
'',
CASE WHEN A.originator='' OR A.originator IS NULL OR A.originator='null' THEN '' ELSE A.originator END,
A.cif_id,
CASE WHEN D.callexecutiondate='' OR D.callexecutiondate IS NULL OR D.callexecutiondate ='null' THEN '' ELSE CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callexecutiondate END END,
CASE WHEN A.originationdate IS NULL THEN '' ELSE A.originationdate END,
CASE WHEN A.request_type='' OR A.request_type IS NULL OR A.request_type='null' THEN '' ELSE A.request_type END,
CASE WHEN a.loan_subtype='' OR a.loan_subtype IS NULL OR a.loan_subtype='null' THEN '' ELSE a.loan_subtype END,
CASE WHEN E.loanamounttxndetails IS NULL OR E.loanamounttxndetails ='null' OR E.loanamounttxndetails='' THEN '0' ELSE e.loanamounttxndetails END,
CASE WHEN E.customerdbrtxndetails IS NULL OR E.customerdbrtxndetails ='null' OR E.customerdbrtxndetails='' THEN '0.00' ELSE E.customerdbrtxndetails END,
'stlment count',
'loan os',
--Here I am inserting the query--
(SELECT
isnull(ab.mycount,0)
FROM
bm_rlos_exttable aa
LEFT OUTER JOIN
(SELECT bpm_referenceno,count(bpm_referenceno) mycount FROM
BM_RLOS_ExistingBMLiabilitiesGrid GROUP BY bpm_referenceno) ab ON aa.bpm_referenceno = ab.bpm_referenceno),
CASE WHEN G.isselected='true' THEN G.insuranceType ELSE '' END,
CASE WHEN E.loantenortxndetails IS NULL OR E.loantenortxndetails='' OR E.loantenortxndetails='null' THEN '' ELSE E.loantenortxndetails END,
CASE WHEN E.interestratetxndetails IS NULL OR E.interestratetxndetails='' OR E.interestratetxndetails='null' THEN '' ELSE E.interestratetxndetails END,
'CHARGE1',
'CHARGE2',
CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callreferenceid ELSE '' END,
'rco',
'tat'
FROM
BM_RLOS_EXTTABLE A WITH (NOLOCK)
INNER JOIN BM_RLOS_BasicLoanDetailsForm B WITH (NOLOCK)
ON A.bpm_referenceno = B.bpm_referenceno
INNER JOIN BM_RLOS_DisbursementCallsGrid D WITH (NOLOCK)
ON A.bpm_referenceno = D.bpm_referenceno
INNER JOIN BM_RLOS_CheckFinalEligibilityForm E WITH (NOLOCK)
ON A.bpm_referenceno = E.bpm_referenceno
INNER JOIN BM_RLOS_ExistingBMLiabilitiesGrid F WITH (NOLOCK)
ON A.bpm_referenceno = F.bpm_referenceno
INNER JOIN BM_RLOS_InsuranceProductSelectionGrid G WITH (NOLOCK)
ON A.bpm_referenceno = G.bpm_referenceno
INNER JOIN BM_RLOS_ChargeAndFeeDetailsForm H WITH (NOLOCK)
ON A.bpm_referenceno = H.bpm_referenceno
INNER JOIN BM_RLOS_DecisionHistoryForm I WITH (NOLOCK)
ON A.bpm_referenceno = I.bpm_referenceno
INNER JOIN wfcurrentroutelogtable J WITH (NOLOCK)
ON A.bpm_referenceno = J.ProcessInstanceId
This should do the trick
SELECT
a.id,
a.name,
b.mysum
FROM
General_Table a
LEFT OUTER JOIN (select bpm_id, SUM(outstandingamount) mysum
from loan_table group by bpm_id) b
ON a.id = b.bpm_id
Edit: subquery changed ( based on your join clause i assumed your id field in the loan_table was bpm_id)
Edit2:
Note i moved your nested query into a new LEFT JOIN in order to make this work.
You cannot use nested query in a select statement if it returns more then 1 record
SELECT
A.bpm_referenceno,
CASE WHEN B.loanbookingbranch='--Select--' or B.loanbookingbranch='null' THEN '' ELSE B.loanbookingbranch END,
CASE WHEN A.branch='' OR A.branch IS NULL OR A.branch='null' THEN '' ELSE A.branch END,
'',
CASE WHEN A.originator='' OR A.originator IS NULL OR A.originator='null' THEN '' ELSE A.originator END,
A.cif_id,
CASE WHEN D.callexecutiondate='' OR D.callexecutiondate IS NULL OR D.callexecutiondate ='null' THEN '' ELSE CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callexecutiondate END END,
CASE WHEN A.originationdate IS NULL THEN '' ELSE A.originationdate END,
CASE WHEN A.request_type='' OR A.request_type IS NULL OR A.request_type='null' THEN '' ELSE A.request_type END,
CASE WHEN a.loan_subtype='' OR a.loan_subtype IS NULL OR a.loan_subtype='null' THEN '' ELSE a.loan_subtype END,
CASE WHEN E.loanamounttxndetails IS NULL OR E.loanamounttxndetails ='null' OR E.loanamounttxndetails='' THEN '0' ELSE e.loanamounttxndetails END,
CASE WHEN E.customerdbrtxndetails IS NULL OR E.customerdbrtxndetails ='null' OR E.customerdbrtxndetails='' THEN '0.00' ELSE E.customerdbrtxndetails END,
'stlment count',
'loan os',
--Here I am inserting the query--
mycount,
CASE WHEN G.isselected='true' THEN G.insuranceType ELSE '' END,
CASE WHEN E.loantenortxndetails IS NULL OR E.loantenortxndetails='' OR E.loantenortxndetails='null' THEN '' ELSE E.loantenortxndetails END,
CASE WHEN E.interestratetxndetails IS NULL OR E.interestratetxndetails='' OR E.interestratetxndetails='null' THEN '' ELSE E.interestratetxndetails END,
'CHARGE1',
'CHARGE2',
CASE WHEN D.calldescription='MG Contract Creation' AND D.callstatus='SUCCESS' THEN D.callreferenceid ELSE '' END,
'rco',
'tat'
FROM
BM_RLOS_EXTTABLE A WITH (NOLOCK)
INNER JOIN BM_RLOS_BasicLoanDetailsForm B WITH (NOLOCK)
ON A.bpm_referenceno = B.bpm_referenceno
INNER JOIN BM_RLOS_DisbursementCallsGrid D WITH (NOLOCK)
ON A.bpm_referenceno = D.bpm_referenceno
INNER JOIN BM_RLOS_CheckFinalEligibilityForm E WITH (NOLOCK)
ON A.bpm_referenceno = E.bpm_referenceno
INNER JOIN BM_RLOS_ExistingBMLiabilitiesGrid F WITH (NOLOCK)
ON A.bpm_referenceno = F.bpm_referenceno
INNER JOIN BM_RLOS_InsuranceProductSelectionGrid G WITH (NOLOCK)
ON A.bpm_referenceno = G.bpm_referenceno
INNER JOIN BM_RLOS_ChargeAndFeeDetailsForm H WITH (NOLOCK)
ON A.bpm_referenceno = H.bpm_referenceno
INNER JOIN BM_RLOS_DecisionHistoryForm I WITH (NOLOCK)
ON A.bpm_referenceno = I.bpm_referenceno
INNER JOIN wfcurrentroutelogtable J WITH (NOLOCK)
ON A.bpm_referenceno = J.ProcessInstanceId
left join
(SELECT bpm_referenceno,count(bpm_referenceno) mycount FROM
BM_RLOS_ExistingBMLiabilitiesGrid GROUP BY bpm_referenceno) ab ON ab.bpm_referenceno = a.bpm_referenceno)
You don't need cursor at all! It's inefficient. This can be done simply by JOINing and GROUPing. Try this query:
select g.id, l.totalLoan from GeneralTable [g]
join (
select id, sum(loan) [totalLoan] from LoanTable
group by id
) [l] on [g].id = [l].id

Case sql not working

I have a select statement I am trying to make for a report. I have it pulling data and everything I need but I noticed that since I have to use the group by it is dropping off rows that do not exist in a table. How can I stop this or make it work.
SELECT Sum(CASE WHEN direction = 'I' THEN 1 ELSE 0 END) InBound,
Sum(CASE WHEN direction = 'O' THEN 1 ELSE 0 END) OutBound,
Sum(CASE WHEN direction = 'I' THEN p.duration ELSE 0 END) InBoundTime,
Sum(CASE WHEN direction = 'O' THEN p.duration ELSE 0 END) OutBoundTime,
u.fullname,
( CASE
WHEN EXISTS (SELECT g.goalamount
FROM [tblbrokergoals] AS g
WHERE ( g.goaldate BETWEEN
'2016-03-21' AND '2016-03-27' ))
THEN
g.goalamount
ELSE 0
END ) AS GoalAmount
FROM [tblphonelogs] AS p
LEFT JOIN [tblusers] AS u
ON u.fullname = p.phonename
LEFT OUTER JOIN [tblbrokergoals] AS g
ON u.fullname = g.brokername
WHERE ( calldatetime BETWEEN '2016-03-21' AND '2016-03-27' )
AND ( u.userid IS NOT NULL )
AND ( u.direxclude <> '11' )
AND u.termdate IS NULL
AND ( g.goaldate BETWEEN '2016-03-21' AND '2016-03-27' )
GROUP BY u.fullname,
g.goalamount;
This works and grabs all the data when the user is in BrokerGoals but, when the user is not in broker goals it just deletes that row on the returned result set. How can I get it so when the user doesnt not exist in the brokergoals table to set that value as 0 or -- so the row does not get deleted.
If you have a brokers table then you can use it for your left join
SELECT b.broker_id, ....
FROM brokers b
LEFT JOIN .... ALL YOUR OTHER TABLES
....
GROUP BY b.broker_id, ....
If your brokers has duplicate names then use
SELECT b.broker_id, ....
FROM (SELECT DISTINCT broker_id
FROM brokers) b
LEFT JOIN .... ALL YOUR OTHER TABLES
....
GROUP BY b.broker_id, ....
SELECT u.FullName,
SUM(CASE WHEN Direction = 'I' THEN 1 ELSE 0 END) AS InBound,
SUM(CASE WHEN Direction = 'O' THEN 1 ELSE 0 END) OutBound,
SUM(CASE WHEN Direction = 'I' THEN p.Duration ELSE 0 END) InBoundTime,
SUM(CASE WHEN Direction = 'O' THEN p.Duration ELSE 0 END) OutBoundTime,
CASE WHEN EXISTS (
SELECT g.GoalAmount
FROM [Portal].[dbo].[tblBrokerGoals] AS g
WHERE g.GoalDate BETWEEN '2016-03-21' AND '2016-03-27'
AND u.FullName = g.BrokerName
) THEN (
SELECT g.GoalAmount
FROM [Portal].[dbo].[tblBrokerGoals] AS g
WHERE g.GoalDate BETWEEN '2016-03-21' AND '2016-03-27'
AND u.FullName = g.BrokerName
) ELSE '0' END AS GoalAmount
FROM [Portal].[dbo].[tblUsers] AS u
LEFT JOIN [Portal].[dbo].[tblPhoneLogs] AS p
ON u.FullName = p.PhoneName
WHERE u.UserID IS NOT NULL
AND u.DirExclude <> '11'
AND u.TermDate IS NULL
AND p.CallDateTime BETWEEN '2016-03-21' AND '2016-03-27'
GROUP BY u.FullName
This is what I ended up doing to fix my problem. I added the Case When Exists statement and in the then statement did the select else it is 0.
Have you tried replacing ( CASE
WHEN EXISTS (SELECT g.goalamount
FROM [tblbrokergoals] AS g
WHERE ( g.goaldate BETWEEN
'2016-03-21' AND '2016-03-27' ))
THEN
g.goalamount
ELSE 0
END ) AS GoalAmount
to just g.goalamount, as you already have that date condition in where clause

Get Count in One to Many relation in sql

here is the link of the related question Related question ,
Now i have a query which gives me the company name exactly as i want
QUERY
SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN a.Name +'(Important) '
WHEN IsHighPriority = 1 THEN a.Name +'(High Priority) '
ELSE a.Name +''
END AS CompanyName
FROM Company a
LEFT JOIN
(
SELECT Name, COUNT(*) totalCoupons
FROM Company
GROUP BY Name
) b ON a.name = b.name
Now i want that In the scenario of (important) we are testing that if company have more then 3 coupons then add (Important) infront of Company name but i want to do that if
a company have more then 3 coupons where
RejectProcessed = 0 and ReviewVerify = 0 and isPublish = 0 and ForSupervisor = 0
then i want to add important infront of that particular company name . So , what should i do .
Please feel free to ask if you need any detail .
Thanks in advance
This query solved my problem
SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN company.Name +' (Important) '
WHEN IsHighPriority = 1 THEN company.Name +' (High Priority) '
ELSE company.Name +''
END AS CompanyName , company.id as Companyid
FROM Company company
left JOIN
(
SELECT co.Name as coName, co.id as coid, COUNT(c.id) totalCoupons
FROM Company co, Coupon c
where c.CompanyId = co.id and c.RejectedProcessed = 1 and c.ReviewVerify = 0 and c.isPublish = 0 and c.ForSupervisor = 0
GROUP BY co.Name, co.id
) b ON company.id = b.coid
#user2193861, is Coupon present in left join with company table..?
LEFT JOIN
(
SELECT Name, COUNT(*) totalCoupons
FROM Coupon
GROUP BY Name
) b ON a.name = b.name
Use this..
SELECT CASE WHEN COALESCE(b.totalCoupons, 0) > 3 THEN a.Name +'(Important) '
WHEN IsHighPriority = 1 THEN a.Name +'(High Priority) '
ELSE a.Name +''
END AS CompanyName
FROM Company a
LEFT JOIN
(
SELECT Name, COUNT(*) totalCoupons
FROM Company C
WHERE
EXISTS(
select 1
from coupon P
where P.RejectProcessed = 0 and P.ReviewVerify = 0
and P.isPublish = 0 and P.ForSupervisor = 0
and P.CompanyName = C.Name
)
and in second query..
use WHERE P.RejectProcessed = 0 and P.ReviewVerify = 0
and P.isPublish = 0 and P.ForSupervisor = 0