Filter result using alias - sql

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

Related

How to speed up a SQL query which is using DISTINCT

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

SQL get fields which are null/empty for each record returned

I have the below query which I'm using to retrieve records which have at least one of the following columns set as NULL or '':
MainImage
Summary
Description
DECLARE #missingFields varchar(100)
SET #missingFields = ''
SELECT
c.[UnitReference] as 'UnitRef',
t.[NodeName] as 'Property',
#missingFields as 'Field/s missing'
FROM [DetailPage] d
INNER JOIN [CRM] c
ON d.ItemID = c.ItemID
INNER JOIN
[Tree] t
ON d.[ID] = t.[ID]
WHERE (ISNULL(d.MainImage, '') = '' OR ISNULL(d.Summary,'') = '' OR ISNULL(d.[Description],'') = '')
AND c.[IsListed] = 1 AND c.[IsMarketed] = 1
This returns the data I want however I also need to build up a string which lists which of the columns is null or empty for the returned record, e.g. "Main Image is empty, Description is empty" when a record has empty MainImage and Description columns.
I've tried:
#missingFields = CASE WHEN ISNULL(MainImage, '') = '' THEN 'Main image is null' ELSE '' END -- etc...
But I can't include this with the data retrieval operations. How would I go about doing this?
SELECT c.[UnitReference] AS 'UnitRef',
t.[NodeName] AS 'Property',
( CASE
WHEN d.MainImage IS NULL
THEN 'Main Image is Null, '
WHEN d.MainImage = ''
THEN 'Main Image is Empty, '
ELSE ''
END )+
( CASE
WHEN d.Summary IS NULL
THEN 'Summary is Null, '
WHEN d.Summary = ''
THEN 'Summary is Empty, '
ELSE ''
END )+
( CASE
WHEN d.[Description] IS NULL
THEN 'Description is Null, '
WHEN d.[Description] = ''
THEN 'Description is Empty, '
ELSE ''
END ) AS MissingFields
FROM [DetailPage] d
INNER JOIN [CRM] c
ON d.ItemID = c.ItemID
INNER JOIN [Tree] t
ON d.[ID] = t.[ID]
WHERE( d.MainImage IS NULL OR d.MainImage = '' )
OR ( d.Summary IS NULL OR d.Summary = '' )
OR ( d.[Description] IS NULL OR d.[Description] = '' )
AND c.[IsListed] = 1
AND c.[IsMarketed] = 1

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' )))

CASE still returns null

Trying to get the output in Dx_3 to print '' if it is NULL but everything I have tried (NULLIF(), COALESCE(), ELSE '', etc) still prints a NULL.
SELECT
#RecordType AS RecordType_1
,AbstractData.AccountNumber AS AcctNum_2
,(SELECT
CASE
WHEN AD.Diagnosis IS NOT NULL THEN AD.Diagnosis
ELSE ''
END
FROM AbsDrgDiagnoses AD
WHERE (AD.DiagnosisSeqID ='1' AND AD.VisitID = AbstractData.VisitID)) AS Dx_3
FROM AbstractData --214
WHERE AbstractData.PtStatus <> 'REF'
SELECT #RecordType AS RecordType_1,
AbstractData.AccountNumber AS AcctNum_2,
COALESCE(AD.Diagnosis, '') AS Dx_3
FROM AbstractData
LEFT JOIN AbsDrgDiagnoses AD ON AD.VisitID = AbstractData.VisitID
WHERE AbstractData.PtStatus <> 'REF' AND AD.DiagnosisSeqID = '1'

Concatenating multiple CASE statements into one alias

After some previous help on how to approach a problem I am having with some legacy code, it seems like the best approach for my issue is to concatenate case statements to return a value I can parse out in PHP.
I am trying to do something like this, but it is returning many rows, and eventually getting this error:
Maximum stored procedure, function, trigger, or view nesting level
exceeded (limit 32).
SELECT org.org_id,
org.org_name_1,
Datename(YEAR, member.enroll_date) AS enroll_year,
Max(CASE
WHEN board.member_from IS NULL THEN 0
ELSE 1
END) AS board_member,
CASE
WHEN ( org.delete_reason = 'OUT'
AND org.org_delete_flag = 'Y'
AND org.org_status_flag = 'C' ) THEN 'out_of_business|'
ELSE ''
END + CASE
WHEN ( stat.carrier = 'BS'
AND stat.status_id IS NOT NULL
AND stat.termination_date IS NULL
AND stat.flat_dues > 0 ) THEN 'insurance_member|'
ELSE ''
END + CASE
WHEN ( stat.carrier = 'BS'
AND stat.status_id IS NOT NULL
AND stat.termination_date IS NULL
AND stat.flat_dues = 0
AND member.status_flag IN( 'C', 'P' ) ) THEN 'insurance_product|'
ELSE ''
END + CASE
WHEN ( member.enroll_date IS NOT NULL
AND member.status_flag NOT IN( 'C', 'P' ) ) THEN 'member_since|'
ELSE ''
END + CASE
WHEN ( org.org_relationship_parent = 'Y'
AND org.dues_category = 'MBR'
AND org.org_status_flag = 'R' ) THEN 'subsidiary_member|'
ELSE ''
END + CASE
WHEN ( org.org_misc_data_9 = 'PAC' ) THEN 'pac|'
ELSE ''
END + CASE
WHEN ( org.dues_category = 'PART' ) THEN 'partner_member|'
ELSE ''
END + CASE
WHEN ( org.dues_category = 'FREE'
AND org.org_status_flag = 'P' ) THEN 'associate_member|'
ELSE ''
END
--ELSE 'non_member'
--END
AS org_status,
60 AS expires_in,
CASE
WHEN stat.dues_type = 'M' THEN
CASE
WHEN ( stat.termination_date IS NULL ) THEN ( stat.flat_dues )
ELSE 0
END
ELSE
CASE
WHEN ( member.payments = 0 ) THEN member.dues_billed_annual
ELSE member.payments
END
END AS dues_level,
CASE
WHEN ( org.affiliate_code = 'PCCE'
AND org.dues_category = 'MBR'
AND org.org_status_flag = 'R' ) THEN 1
ELSE 0
END AS pcce_membr,
-- '$'+CONVERT(VARCHAR,#dues) AS dues_level,
Ltrim(#product_level) AS product_level,
Ltrim(#involve_level) AS involvement_level
FROM organiz AS org
LEFT JOIN affilbil AS member
ON member.status_id = org.org_id
AND member.dues_category = 'MBR'
LEFT JOIN individu AS ind
ON ind.org_id = org.org_id
LEFT JOIN commembr AS board
ON board.status_id = ind.ind_id
AND board.committee_code = '5'
AND board.member_to IS NULL
LEFT JOIN statinsmorn AS stat
ON stat.status_id = org.org_id
AND stat.carrier = 'BS'
AND stat.planz = 'PCI'
WHERE org.org_id = #org_id
GROUP BY org.org_id,
org.org_name_1,
member.enroll_date,
org.delete_reason,
org.org_status_flag,
org.org_delete_flag,
stat.status_id,
stat.flat_dues,
stat.dues_type,
stat.termination_date,
org.org_misc_data_9,
org_relationship_parent,
org.dues_category,
member.status_flag,
member.dues_billed_annual,
member.payments,
stat.carrier,
org.Affiliate_Code
Well, this is embarrassing.
When I was making my changes to the stored procedure, I had inadvertently placed a call to the same procedure at the bottom. So I was recursively calling the same procedure over and over again. DOH.