How to speed up a SQL query which is using DISTINCT - sql

From what I have read about this it seems like the best solution is to create an INDEX but I am not sure which columns I should be creating indexes for. This is my first time working with SQL indexes.
If I remove the DISTINCT call from this query I get over 1000 results in just over a second. However with the DISTINCT call it returns the results in 10 seconds (obviously without the duplicates).
If anyone has any alternative solutions I am all ears.
This is the query (the second SELECT is where the DISTINCT function is called):
SELECT
Sku,
Name,
ccp.Polygon,
MarketAvailability,
Coverage,
Range
FROM
(SELECT DISTINCT
dbo.CatalogEntry.CatalogEntryId as Id,
dbo.CatalogEntry.Code as Sku,
CoverageNode.Name as Coverage,
RangeNode.Name as [Range],
(SELECT CatalogContentProperty.LongString
FROM CatalogContentProperty
WHERE MetaFieldName = 'ItemChartName'
AND (CatalogContentProperty.LongString IS NOT NULL)
AND (CatalogContentProperty.ObjectId = dbo.CatalogEntry.CatalogEntryId)) AS [Name],
(SELECT CatalogContentProperty.LongString
FROM CatalogContentProperty
WHERE MetaFieldName = 'MarketAvailabilityDetailsCollection'
AND (CatalogContentProperty.LongString IS NOT NULL)
AND (CatalogContentProperty.ObjectId = dbo.CatalogEntry.CatalogEntryId)) AS MarketAvailability
FROM
dbo.CatalogEntry
INNER JOIN
dbo.NodeEntryRelation ON dbo.CatalogEntry.CatalogEntryId = dbo.NodeEntryRelation.CatalogEntryId
INNER JOIN
dbo.CatalogNode AS CoverageNode ON dbo.NodeEntryRelation.CatalogNodeId = CoverageNode.CatalogNodeId
INNER JOIN
dbo.CatalogNode AS RangeNode ON CoverageNode.ParentNodeId = RangeNode.CatalogNodeId
INNER JOIN
dbo.CatalogContentProperty ON dbo.CatalogEntry.CatalogEntryId = dbo.CatalogContentProperty.ObjectId
INNER JOIN
dbo.CatalogNode AS ModelNode ON RangeNode.ParentNodeId = ModelNode.CatalogNodeId
INNER JOIN
dbo.CatalogNode AS BrandNode ON ModelNode.ParentNodeId = BrandNode.CatalogNodeId
WHERE
(dbo.CatalogEntry.ClassTypeId = N'Variation') AND
(dbo.CatalogContentProperty.MetaFieldName = N'ItemIsChart') AND
RangeNode.Name != 'C-MAP' AND
(BrandNode.Name = '' OR '' = '' OR '' IS NULL) AND
(ModelNode.Name = '' OR '' = '' OR '' IS NULL) AND
(CoverageNode.Name = '' OR '' = '' OR '' IS NULL) AND
(RangeNode.Name = '' OR '' = '' OR '' IS NULL)
) AS CmapResults
INNER JOIN
(SELECT
GEOMETRY::STGeomFromText(CatalogContentProperty.LongString,4326) AS PolygonGeometry,
CatalogContentProperty.LongString AS Polygon,
CatalogContentProperty.ObjectId
FROM
CatalogContentProperty
WHERE
MetaFieldName = 'ItemChartCoordinates' AND
(CatalogContentProperty.LongString IS NOT NULL)) ccp ON ccp.ObjectId = CmapResults.Id
WHERE
((GEOGRAPHY::STGeomFromText(PolygonGeometry.MakeValid().STUnion(PolygonGeometry.MakeValid().STStartPoint()).STAsText(), 4326).STDistance(GEOGRAPHY::STGeomFromText('POINT(50.9835929 -1.4205852)', 4326)) / 1609.344) <= 100 OR 'POINT(50.9835929 -1.4205852)' IS NULL)
AND MarketAvailability IS NOT NULL
ORDER BY
GEOGRAPHY::STGeomFromText(PolygonGeometry.MakeValid().STUnion(PolygonGeometry.MakeValid().STStartPoint()).STAsText(), 4326).STArea() DESC;
I am using SQL Server Management Studio 2012. The aim is to get the query with the DISTINCT call to return in the same amount of time as the query would without the DISTINCT call.

Your query looks a bit complicated. Will this one produce the same output?
SELECT DISTINCT ce.Code as Sku
, max(case when ccp.MetaFieldName = 'ItemChartName' then ccp.LongString end) as 'Name'
, max(case when ccp.MetaFieldName = 'MarketAvailabilityDetailsCollection' then ccp.LongString end) as 'MarketAvailability'
, max(case when ccp.MetaFieldName = 'ItemChartCoordinates' then ccp.LongString end) as 'Polygon'
, CoverageNode.Name as Coverage
, RangeNode.Name as 'Range'
FROM dbo.CatalogEntry ce
INNER JOIN dbo.NodeEntryRelation ner ON ce.CatalogEntryId = ner.CatalogEntryId
INNER JOIN dbo.CatalogNode CoverageNode ON dbo.NodeEntryRelation.CatalogNodeId = CoverageNode.CatalogNodeId
INNER JOIN dbo.CatalogNode RangeNode ON CoverageNode.ParentNodeId = RangeNode.CatalogNodeId
INNER JOIN dbo.CatalogContentProperty ccp ON ce.CatalogEntryId = ccp.ObjectId
INNER JOIN dbo.CatalogNode ModelNode ON RangeNode.ParentNodeId = ModelNode.CatalogNodeId
INNER JOIN dbo.CatalogNode BrandNode ON ModelNode.ParentNodeId = BrandNode.CatalogNodeId
WHERE ce.ClassTypeId = N'Variation'
and ccp.MetaFieldName = N'ItemIsChart'
and RangeNode.Name != 'C-MAP'
--and (BrandNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
--and (ModelNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
--and (CoverageNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
--and (RangeNode.Name = '' OR '' = '' OR '' IS NULL) -- always true
and (GEOGRAPHY::STGeomFromText(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STUnion(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STStartPoint()).STAsText(), 4326).STDistance(GEOGRAPHY::STGeomFromText('POINT(50.9835929 -1.4205852)', 4326)) / 1609.344) <= 100 -- OR 'POINT(50.9835929 -1.4205852)' IS NULL -- redundant
)
and max(case when ccp.MetaFieldName = 'MarketAvailabilityDetailsCollection' then ccp.LongString end)
ORDER BY GEOGRAPHY::STGeomFromText(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STUnion(GEOMETRY::STGeomFromText(ccp.LongString,4326).MakeValid().STStartPoint()).STAsText(), 4326).STArea() DESC;

So the answer is my case was to remove the DISTINCT and to do the duplicate removing using LINQ! Load times went from 10-11ish seconds to 4-5ish seconds

Related

Filter result using alias

I have a query like this
SELECT
Type = TXL.Descript, Jurisdiction = CASE WHEN TX.State = 'KD' THEN 'FD'
WHEN TX.County > '' AND TX.County IS NOT NULL THEN 'Local' ELSE 'Country' END,
State = CASE WHEN TX.State = 'FD' OR (TX.County > '' AND TX.County IS NOT NULL) THEN '' ELSE (select top 1 istIntlStateDesc from IntStateM ISM where ISM.istIntlStateCode = TX.MtcState) END,
Local = CASE WHEN TX.County > '' AND TX.County IS NOT NULL THEN TX.MtcCounty ELSE '' END,
TaxCode = TX.TaxCode, TaxDescription = TX.TaxCodeDesc, EffectiveDate = ET.EtxEffectiveDate,
Taxable = ''
FROM
ETaX ET WITH (NOLOCK)
INNER JOIN TxCast TX on ET.Code = TX.TaxCode
INNER JOIN TxLMast TXL on TXL.TCode = TX.Tax
WHERE
ET.TDate <= GETDATE()
AND ET.SDate > GETDATE()
In the UI I have a table and I want to filer each column by passing the column name and what my code is doing is adding an AND condition to the WHERE clause while filtering but if I am passing the alias name (Ex. Jurisdiction) I am getting an error like - Invalid column name 'Jurisdiction', I also can't pass the actual column name as I am using case statement in the query, for example alias Jurisdiction value is coming by combing 2 column name so, is there any way it will work even passing the alias name or any better way to do it like dynamic SQL or any other workaround?
If I understand correctly, you want to filter by your "aliased" fields. To do so, you have 2 options:
Use subquery writing a SELECT FROM your entire query and then filtering by Jurisdiction:
SELECT * FROM
(SELECT
Type = TXL.Descript, Jurisdiction = CASE WHEN TX.State = 'KD' THEN 'FD'
WHEN TX.County > '' AND TX.County IS NOT NULL THEN 'Local' ELSE 'Country' END,
State = CASE WHEN TX.State = 'FD' OR (TX.County > '' AND TX.County IS NOT NULL) THEN '' ELSE (select top 1 istIntlStateDesc from IntStateM ISM where ISM.istIntlStateCode = TX.MtcState) END,
Local = CASE WHEN TX.County > '' AND TX.County IS NOT NULL THEN TX.MtcCounty ELSE '' END,
TaxCode = TX.TaxCode, TaxDescription = TX.TaxCodeDesc, EffectiveDate = ET.EtxEffectiveDate,
Taxable = ''
FROM
ETaX ET WITH (NOLOCK)
INNER JOIN TxCast TX on ET.Code = TX.TaxCode
INNER JOIN TxLMast TXL on TXL.TCode = TX.Tax
WHERE
ET.TDate <= GETDATE()
AND ET.SDate > GETDATE()) AS AUX_QUERY
WHERE
Jurisdiction = -your condition here-
(Note now Jurisdiction is a result field from AUX_QUERY)
Repeat the full CASE WHEN TX.State = 'KD' THEN 'FD' WHEN TX.County > '' AND TX.County IS NOT NULL THEN 'Local' ELSE 'Country' END that you called Jurisdiction in the WHERE clause (or wherever you want to use those calculated fields:
SELECT
Type = TXL.Descript, Jurisdiction = CASE WHEN TX.State = 'KD' THEN 'FD'
WHEN TX.County > '' AND TX.County IS NOT NULL THEN 'Local' ELSE 'Country' END,
State = CASE WHEN TX.State = 'FD' OR (TX.County > '' AND TX.County IS NOT NULL) THEN '' ELSE (select top 1 istIntlStateDesc from IntStateM ISM where ISM.istIntlStateCode = TX.MtcState) END,
Local = CASE WHEN TX.County > '' AND TX.County IS NOT NULL THEN TX.MtcCounty ELSE '' END,
TaxCode = TX.TaxCode, TaxDescription = TX.TaxCodeDesc, EffectiveDate = ET.EtxEffectiveDate,
Taxable = ''
FROM
ETaX ET WITH (NOLOCK)
INNER JOIN TxCast TX on ET.Code = TX.TaxCode
INNER JOIN TxLMast TXL on TXL.TCode = TX.Tax
WHERE
ET.TDate <= GETDATE()
AND ET.SDate > GETDATE()) AS AUX_QUERY
AND
CASE WHEN TX.State = 'KD' THEN 'FD'
WHEN TX.County > '' AND TX.County IS NOT NULL THEN 'Local' ELSE 'Country' END = -your condition here-
Aliases cannot be used like that, look at this example
declare #table1 table (id int, text1 varchar(50), text2 varchar(50))
insert into #table1 values (1, 'one', 'two')
select t1.id,
fullname = t1.text1 + ' ' + t1.text2
from #table1 t1
where fullname = 'one two'
This will throw this exception
Invalid column name 'fullname'
The most simple solution (imho) is this
select t.id,
t.fullname
from ( select t1.id,
fullname = t1.text1 + ' ' + t1.text2
from #table1 t1
) t
where t.fullname = 'one two'
This allows the database to fully evaluate the aliased columns, and therefore it will known them so you can use the aliased columns just like other columns

SQL Query - How to suppress repeating values in the result set?

I'm trying to suppress the repeating values in TotalCarton column. Have tried to replace the value either blank or null but went failed. Any help?
Here is the SQL Script:
SELECT ORDERS.StorerKey,
ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = ( CASE BAX_PACK_DTL.PackType WHEN 'C' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
TotalPallet = ( CASE BAX_PACK_DTL.PackType WHEN 'P' THEN Count(DISTINCT(BAX_PACK_DTL.OuterPackID))
ELSE 0 END ),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'C' AND PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE PackType = 'P' AND PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM ORDERS WITH (NOLOCK) INNER JOIN ORDERDETAIL WITH (NOLOCK) ON ORDERS.StorerKey = ORDERDETAIL.StorerKey
AND ORDERS.OrderKey = ORDERDETAIL.OrderKey
INNER JOIN PICKDETAIL WITH (NOLOCK) ON ORDERDETAIL.StorerKey = PICKDETAIL.StorerKey
AND ORDERDETAIL.OrderKey = PICKDETAIL.OrderKey
AND ORDERDETAIL.OrderLineNumber = PICKDETAIL.OrderLineNumber
INNER JOIN BAX_PACK_DTL WITH (NOLOCK) ON PICKDETAIL.OrderKey = BAX_PACK_DTL.OrderKey
AND PICKDETAIL.PickDetailKey = BAX_PACK_DTL.PickDetailKey
WHERE (SELECT COUNT(DISTINCT(ORDERKEY)) FROM PICKDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey ) > 0
AND BAX_PACK_DTL.PackKey = '0000000211'
AND BAX_PACK_DTL.OuterPackID IN
('P111111111',
'P22222222',
'P33333333')
GROUP BY ORDERS.StorerKey,
ORDERS.OrderKey,
ORDERS.ExternOrderKey,
ORDERS.HAWB,
ORDERS.SO,
ORDERS.EditWho,
ORDERS.AddDate,
PICKDETAIL.WaveKey,
BAX_PACK_DTL.OuterPackID,
BAX_PACK_DTL.PackKey,
BAX_PACK_DTL.PackType
ORDER BY BAX_PACK_DTL.OuterPackID ASC
Below is the current result set based on the query above.
Your code looks really strange. I would expect the query to use conditional aggregation and look more like this:
SELECT ORDERS.StorerKey, ORDERS.OrderKey,
PackKey = (SELECT MAX(PackKey) FROM BAX_PACK_DTL WITH (NOLOCK) WHERE ORderKey = ORDERS.OrderKey),
PackHU = BAX_PACK_DTL.OuterPackID,
SalesOrderNum = ( SELECT Upper(Max(ORDERDETAIL.CustShipInst01)) FROM ORDERDETAIL WITH (NOLOCK) WHERE OrderKey = ORDERS.OrderKey),
DeliveryNum = Upper(ORDERS.ExternOrderKey),
TotalCarton = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'C' THEN BAX_PACK_DTL.OuterPackID END),
TotalPallet = COUNT(DISTINCT CASE BAX_PACK_DTL.PackType WHEN 'P' THEN BAX_PACK_DTL.OuterPackID END),
SumCarton = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'C' AND pbd.PackKey = '0000000211'),
SumPallet = (SELECT COUNT(DISTINCT(OuterPackSeq)) FROM BAX_PACK_DTL bpd WHERE pbd.PackType = 'P' AND pbd.PackKey = '0000000211'),
AddWho = Upper(ORDERS.EditWho),
ORDERS.AddDate
FROM . . .
GROUP BY ORDERS.StorerKey, ORDERS.OrderKey, Upper(ORDERS.ExternOrderKey),
Upper(ORDERS.EditWho), ORDERS.AddDate;
This may not be exact. You have not qualified column names, given the table structure, and are using very arcane query syntax, mixing subqueries and aggregations. But it should give an idea.

How to use bitwise operator in existing sql query?

Here is my sql query. I have column name "ExpenseBucketCoverage" in claim table in which I am storing bitwise operators store multiple values in one column like below
MED_COPAY = 1, MED_DED= 10, MED_COINS = 100, RX_COPAY = 1, RX_DED= 10, RX_COINS = 100
I want to replace hard coded value like MED_COPAY, MED_COINS, MED_DED, RX_DED, RX_COINS & RX_COPAY in query by using ExpenseBucketCoverage column value. Can some one please tell me how can I do that?
Someone has suggested me below soultion
retrieve data from claim and left joining the first matched record in eligibility. And then add custom code to loop through the datarows to split the rows by covered expense bucket, and set the service category code in-memory column based on the ExpenseBucketCoverage value for the claim.
SELECT
e.categoryid,
c.servicetype,
'II' AS RepordType,
e.TPAId AS TPA_Id,
e.EmployerCode,
e.SubscriberId,
e.MemberID,
c.ServiceFrom,
c.ServiceTo,
CASE
WHEN e.categoryid IN( 'MED_DED', 'RX_DED' ) THEN
deductible
WHEN e.categoryid IN( 'MED_COINS', 'RX_COINS' ) THEN
isnull(coins,0)
WHEN e.categoryid IN( 'MED_COPAY', 'RX_COPAY' ) THEN
copay
ELSE 0
END AS ClaimAmount,
'' AS AccountTypeCode,
'1' ClaimsCrossoverAutoPay,
e.CategoryId,
CASE c.ServiceType
WHEN 'H' THEN
CASE e.PayeeIndicator
WHEN 'N' THEN '0'
WHEN 'Y' THEN '1'
END
WHEN 'P' THEN '0'
END AS PayProvider,
CASE c.ServiceType
WHEN 'H' THEN
CASE PayeeIndicator
WHEN 'N' THEN '0'
WHEN 'Y' THEN '1'
END
WHEN 'P' THEN '0'
END AS ReimbursementMethod,
CASE c.ServiceType
WHEN 'H' THEN c.Provider
WHEN 'P' THEN ''
END AS ProviderId,
'1' EnforceAccountEffectiveDates,
c.Id,
c.ClaimNumber + e.CategoryId as 'ExternalClaimNumber',
c.ProviderName,
c.CarrierId + ';' + c.SourceClaimNumber AS Notes
FROM Claim c
INNER JOIN Eligibility e ON e.TPAId = c.TPAId AND e.EIN = c.EIN AND
c.Processed = 'Y' AND e.FilterType = 'Eligibility'
AND c.TPAId='PrimePay'
AND (c.ServiceFrom >= e.BenefitEffectiveDate
AND c.ServiceFrom <=e.BenefitTermDate)
AND ( ( c.PayorID = c.PatientSSN
AND e.SubscriberSSN = c.PatientSSN
AND (c.EmployeeFirstName = c.PatientFirstName
AND c.EmployeeLastName = c.PatientLastName)
AND(e.MemberSSN = '' OR e.MemberSSN = NULL)
AND(e.MemberFirstName = '' OR e.MemberFirstName = NULL)
AND(e.MemberLastName = '' OR e.MemberLastName = NULL))
OR((c.PayorID != c.PatientSSN AND e.MemberSSN = c.PatientSSN
AND e.MemberFirstName = c.PatientFirstName
AND e.MemberLastName = c.PatientLastName)
OR(c.PayorID != c.PatientSSN AND e.MemberFirstName = c.PatientFirstName
AND e.MemberLastName= c.PatientLastName)))
AND (( c.Servicetype ='P'
AND e.CategoryID IN('RX_COINS','RX_COPAY', 'RX_DED' ))
OR ( c.Servicetype = 'H'
AND e.CategoryID IN( 'MED_COINS','MED_COPAY', 'MED_DED' )))

Performance Issue in Select groupby

I have following block of code and It takes approx 4-5 minutes to execute. All the tables in this block has large amount of data.
Select
spa.Student_Id,
Cast(Case When ISNULL(#PeriodNumbers, '') = '' Then --PeriodCode Come
CPS.PeriodIdentifier
Else --period number come
Cast(SPA.PeriodNumber as varchar)
End As varchar) As Period,
IsNULL(Count(*), 0) As TotalCount,
AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar) As PeriodNumber
From
(Select Student_ID
From OpenXml(#Handle,'/NewDataSet/Table', 2)
With (Student_ID int) As DT
) FilterDT
Inner Join
dbo.StudentPeriodicAttendanceArchive SPA WITH(NOLOCK) On FilterDT.Student_ID = SPA.Student_ID
Inner Join
dbo.AcademicYear AY WITH(NOLOCK) On AY.AYIdentifier = #AYIdentifier
And AY.School_Domain = #School_Domain
Inner join
dbo.CPsession CPS WITH(NOLOCK) On CPS.SSEC_ID = SPA.SSEC_ID
And CPS.PeriodNumber= spa.periodnumber
And CPS.School_Domain = #School_Domain
And CPS.AYIdentifier = #AYIdentifier
And (CPS.CPSDelStatus = 0 Or CPS.CPSDelStatus Is Null)
Inner Join
dbo.BellTimingScheduleStructure BTSS WITH(NOLOCK) ON BTSS.DayNumber = CPS.WD_ID
And BTSS.SchedulingWeek = CPS.Week
Inner Join
dbo.ClassPeriods CP WITH(NOLOCK) On CP.CP_Id = CPS.CP_ID
And BTSS.CPR_ID = CP.CPR_ID
And BTSS.WeekDay = Case When BTSS.CPRType='D' Then BTSS.WeekDay Else CP.WD_ID End
And BTSS.DayNumber = Case When BTSS.CPRType='D' Then CP.WD_ID Else BTSS.DayNumber End
And BTSS.SchedulingWeek = Case When BTSS.CPRType='W' Then BTSS.SchedulingWeek Else CP.Week End
And BTSS.DateItem = SPA.Attdate
And CP.CPDelStatus = '0'
And IsNull(CP.IsLocked, '0') = '0'
Inner Join
dbo.AttendanceCodes AC WITH(NOLOCK) On AC.AC_ID = SPA.AttCode_ID
Where
SPA.School_Domain = #School_Domain
And AttDate >= Case When #IsYearLongTotals=1 then AY.AYStartDate Else #ActualStartDate End
And AttDate <= Case When #IsYearLongTotals=1 then AY.AYEndDate Else #ActualEndDate End
And IsNull(#Subject_ID, -1) = Case When IsNull(#Subject_ID, -1) <> -1
Then CPS.Subject_ID
Else IsNull(#Subject_ID, -1)
End
Group By
spa.Student_ID,
Cast(Case When ISNULL(#PeriodNumbers, '') = ''
Then CPS.PeriodIdentifier
Else
Cast(SPA.PeriodNumber as varchar)
End As varchar), AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar)
I have a table StudentPeriodicAttendanceArchive which contains attendance information. I want to calculate total present and absent count.
Please suggest what should I do to improve the performance. I am using SQL Server 2008 R2

Flag parameter doesn't work correctly (SQL)

I have an "AcctMgr_Flag" that designates a person as the account manager. This is on the table Company_Team. If I send parameter #acctmgr as 'true', I want to return only Activities where #member is the account manager. If #acctmgr is not true, I do not care whether AcctMgr_Flag is true or not.
Every Activity in SO_Activity has an "Assigned_To" column which designates a member_recid. Every Member in Company_Team has an AcctMgr_Flag and Company_RecID. Every Member in v_rpt_Member has a member_recid and a Company_recid.
Here is my code
SELECT v_rpt_Company.Company_Name, SO_Activity.Subject, SO_Activity.Notes,
SO_Activity.Date_Closed, SO_Activity.Last_Update, v_rpt_Member.Member_ID,
v_rpt_ActivityType.SO_Activity_Type_Desc,
v_rpt_ActivityStatus.SO_Act_Status_Desc
FROM v_rpt_Company
LEFT OUTER JOIN SO_Activity
ON v_rpt_Company.Company_RecID = SO_Activity.Company_RecID
LEFT OUTER JOIN v_rpt_Member
ON SO_Activity.Assign_To = v_rpt_Member.Member_ID
LEFT OUTER JOIN Company_Team
ON v_rpt_Member.Member_RecID = Company_Team.Member_RecID AND
v_rpt_Company.Company_RecID = Company_Team.Company_RecID
LEFT OUTER JOIN v_rpt_ActivityType
ON SO_Activity.SO_Activity_Type_RecID=v_rpt_ActivityType.SO_Activity_Type_RecID
LEFT OUTER JOIN v_rpt_ActivityStatus
ON SO_Activity.so_act_status_recid = v_rpt_ActivityStatus.SO_Act_Status_RecID
WHERE (Company_Team.AcctMgr_Flag =
CASE WHEN #acctmgr = 'true' THEN 1 ELSE Company_Team.AcctMgr_Flag END) AND
(SO_Activity.Assign_To = #member) AND
(v_rpt_ActivityStatus.SO_Act_Status_Desc =
CASE WHEN #act_status IS NULL
THEN v_rpt_ActivityStatus.so_act_status_desc ELSE #act_status END) AND
(v_rpt_Company.Company_RecID =
CASE WHEN #company = '' THEN v_rpt_Company.Company_RecID ELSE #company END) AND
(SO_Activity.Last_Update >= CONVERT(datetime, #date_start, 101)) AND
(SO_Activity.Last_Update <= CONVERT(datetime, #date_end, 101))
GROUP BY v_rpt_Company.Company_Name, SO_Activity.Subject, SO_Activity.Notes,
SO_Activity.Date_Closed, SO_Activity.Last_Update, v_rpt_Member.Member_ID,
v_rpt_ActivityType.SO_Activity_Type_Desc,
v_rpt_ActivityStatus.SO_Act_Status_Desc
ORDER BY v_rpt_Company.Company_Name, SO_Activity.Last_Update DESC
Instead of
(Company_Team.AcctMgr_Flag = CASE WHEN #acctmgr = 'true' THEN 1 ELSE Company_Team.AcctMgr_Flag END)
Put this
(#acctmgr != 'true' or Company_Team.AcctMgr_Flag = 1)