r270ba
asked on
Select Count Subquery
I need to get the [Opportunity Count] field to return a count based on the SELECT Count(*) subquery written.
See code below and look for the [Opportunity Count] column.
See code below and look for the [Opportunity Count] column.
/*
Type Codes
Account - 1
Appointmenet - 4201
Opportunity - 3
*/
SELECT Subject,
RegardingObjectIdName,
Description,
CreatedByName,
ScheduledEnd,
ActualEnd,
CreatedOn,
RegardingObjectTypeCode,
[Regarding]=CASE WHEN RegardingObjectTypeCode='1' THEN 'Account' WHEN RegardingObjectTypeCode='4201' THEN 'Appointment' WHEN RegardingObjectTypeCode='3' THEN 'Opportunity' ELSE 'n/a' END,
[Opportunity Count]= SELECT COUNT(*) FROM dbo.Opportunity o WHERE StateCode='0' AND o.AccountId=RegardingObjectId
FROM dbo.Appointment
ORDER BY ScheduledEnd desc
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Or, performance-wise, better yet,
SELECT Subject,
RegardingObjectIdName,
Description,
CreatedByName,
ScheduledEnd,
ActualEnd,
CreatedOn,
RegardingObjectTypeCode,
[Regarding]=CASE WHEN RegardingObjectTypeCode='1 ' THEN 'Account' WHEN RegardingObjectTypeCode='4 201' THEN 'Appointment' WHEN RegardingObjectTypeCode='3 ' THEN 'Opportunity' ELSE 'n/a' END,
[Opportunity Count]
FROM dbo.Appointment inner join
(Select AccountID, COUNT(*) as [opportunity Count] FROM dbo.Opportunity
WHERE StateCode='0'
group by AccountID
) as O
on o.AccountId=RegardingObjec tId
ORDER BY ScheduledEnd desc
SELECT Subject,
RegardingObjectIdName,
Description,
CreatedByName,
ScheduledEnd,
ActualEnd,
CreatedOn,
RegardingObjectTypeCode,
[Regarding]=CASE WHEN RegardingObjectTypeCode='1
[Opportunity Count]
FROM dbo.Appointment inner join
(Select AccountID, COUNT(*) as [opportunity Count] FROM dbo.Opportunity
WHERE StateCode='0'
group by AccountID
) as O
on o.AccountId=RegardingObjec
ORDER BY ScheduledEnd desc
[Opportunity Count]= (SELECT COUNT(*) FROM dbo.Opportunity o WHERE StateCode='0' AND o.AccountId=dbo.Appointmen