I need to filter out distinct rows from below query without using distinct keyword.
So in the CM.PfmFolderMstIpMap Table there are duplicate F.Id's or PMMAP.PfmFolderFK Id's so I want to filter out non-duplicate ones
SELECT F.Id,
F.folderno,
F.folderstatusdate,
(SELECT codedesc
FROM cm.codetable
WHERE id = F.FolderStatusCode) 'FolderStatus',
(SELECT codedesc
FROM cm.codetable
WHERE id = F.FolderLocationCode) 'Location',
F.volume,
F.sdexhibits,
F.cost,
F.remarks
FROM cm.pfmfolder F WITH(nolock)
INNER JOIN cm.pfmfoldermstipmap PMMAP WITH(nolock)
ON PMMAP.pfmfolderfk = F.id
INNER JOIN cm.mstip MST WITH(nolock)
ON MST.id = PMMAP.mstipfk
LEFT JOIN tm.mstirsdmstipmap IRMAP WITH(nolock)
ON IRMAP.mstipfk = MST.id
LEFT JOIN tm.mstirsd IRSD WITH(nolock)
ON IRSD.id = IRMAP.mstirsdfk
LEFT JOIN tm.mstir IR WITH(nolock)
ON IR.id = IRSD.mstirfk
LEFT JOIN tm.mstiabasicmark IABM
ON IABM.basicmarknbr = MST.applnnbr
LEFT JOIN tm.mstia IA
ON IA.id = IABM.mstiafk
WHERE ( #FolderNbr IS NULL
OR F.folderno LIKE + #FolderNbr + '%' )
AND ( #ApplnNbr IS NULL
OR MST.applnnbr LIKE + #ApplnNbr + '%' )
AND ( #IrNbr IS NULL
OR IR.irnbr LIKE + #IrNbr + '%' )
AND ( #IaNbr IS NULL
OR IA.ianbr LIKE + #IaNbr + '%' )
AND ( #FolderStatusCode IS NULL
OR F.folderstatuscode = #FolderStatusCode )
AND ( #FolderLocationCode IS NULL
OR F.folderlocationcode = #FolderLocationCode )
AND ( F.folderstatusdate >= #FolderStatusDateFrom
AND F.folderstatusdate < #FolderStatusDateTo )
AND MST.registrycode = #RegistryCode
AND PMMAP.deletedby IS NULL
As Sam said Distinct is the best option. Otherwise use Group by using all columns
You can use Row_Number feature too
Try this
SELECT * FROM
(
SELECT F.Id,
F.folderno,
F.folderstatusdate,
(SELECT codedesc
FROM cm.codetable
WHERE id = F.FolderStatusCode) 'FolderStatus',
(SELECT codedesc
FROM cm.codetable
WHERE id = F.FolderLocationCode) 'Location',
F.volume,
F.sdexhibits,
F.cost,
F.remarks,
Row_number() OVER(partition BY F.Id ORDER BY (SELECT NULL) ASC) RN
FROM cm.pfmfolder F WITH(nolock)
INNER JOIN cm.pfmfoldermstipmap PMMAP WITH(nolock)
ON PMMAP.pfmfolderfk = F.id
INNER JOIN cm.mstip MST WITH(nolock)
ON MST.id = PMMAP.mstipfk
LEFT JOIN tm.mstirsdmstipmap IRMAP WITH(nolock)
ON IRMAP.mstipfk = MST.id
LEFT JOIN tm.mstirsd IRSD WITH(nolock)
ON IRSD.id = IRMAP.mstirsdfk
LEFT JOIN tm.mstir IR WITH(nolock)
ON IR.id = IRSD.mstirfk
LEFT JOIN tm.mstiabasicmark IABM
ON IABM.basicmarknbr = MST.applnnbr
LEFT JOIN tm.mstia IA
ON IA.id = IABM.mstiafk
WHERE ( #FolderNbr IS NULL
OR F.folderno LIKE + #FolderNbr + '%' )
AND ( #ApplnNbr IS NULL
OR MST.applnnbr LIKE + #ApplnNbr + '%' )
AND ( #IrNbr IS NULL
OR IR.irnbr LIKE + #IrNbr + '%' )
AND ( #IaNbr IS NULL
OR IA.ianbr LIKE + #IaNbr + '%' )
AND ( #FolderStatusCode IS NULL
OR F.folderstatuscode = #FolderStatusCode )
AND ( #FolderLocationCode IS NULL
OR F.folderlocationcode = #FolderLocationCode )
AND ( F.folderstatusdate >= #FolderStatusDateFrom
AND F.folderstatusdate < #FolderStatusDateTo )
AND MST.registrycode = #RegistryCode
AND PMMAP.deletedby IS NULL
) AS T
WHERE RN = 1
Distinct is the best option. Otherwise use Group by using all columns
Related
I need some help with a subquery. My test column sometimes comes back NULL and if so I want to filter those out of my results set.
My stored procedure looks like this
SELECT
pl.Id AS Id,
pl.Name AS Name,
f.[Url] AS PrimaryImageUrl,
up.Id AS MemberId,
up.ProfessionalName,up.
AvatarUrl,
test = (SELECT
c.Id AS Id,
c.Name AS Name,
c.ContentImageUrl AS ImageUrl,
c.Price AS Price,
c.BPM AS BPM,
f.Id AS 'File.Id',
f.Url AS 'File.Name',
TotalCount = COUNT (c.Id) OVER()
FROM
dbo.Content c
INNER JOIN
dbo.PlayListContents pm ON c.Id = pm.ContentId
AND pm.PlaylistId = pl.Id
INNER JOIN
dbo.Files f ON c.ContentFileId = f.Id
FOR JSON PATH),
TotalCount = COUNT(1) OVER()
FROM
dbo.Playlist pl
INNER JOIN
dbo.UserProfiles up ON pl.UserId = up.UserId
INNER JOIN
[dbo].[Files] AS f ON pl.[PrimaryImageId] = f.[Id]
WHERE
(pl.Name LIKE '%' + #searchInput + '%')
AND test IS NOT NULL
Why is this last line, AND test IS NOT NULL invalid? I need my result set to have all results with test being NOT NULL
Try this
SELECT * FROM
(Select pl.Id as Id
,pl.Name as Name
,f.[Url] as PrimaryImageUrl
,up.Id as MemberId
,up.ProfessionalName
,up.AvatarUrl
,test = ( select c.Id as Id
,c.Name as Name
,c.ContentImageUrl as ImageUrl
,c.Price as Price
,c.BPM as BPM
,f.Id as 'File.Id'
,f.Url as 'File.Name'
,TotalCount = count(c.Id)Over()
from dbo.Content c
inner join dbo.PlayListContents pm on c.Id = pm.ContentId and pm.PlaylistId = pl.Id
inner join dbo.Files f on c.ContentFileId = f.Id
for json path)
--,TotalCount = COUNT(1) OVER()
from dbo.Playlist pl
inner join dbo.UserProfiles up on pl.UserId = up.UserId
inner join [dbo].[Files] as f ON pl.[PrimaryImageId] = f.[Id]
where ( pl.Name LIKE '%' + #searchInput + '%')) a
WHERE a.test IS NOT NULL
Columns in the SELECT are not available in the WHERE, due to SQL's logical order of operations.
Instead, place the value in CROSS APPLY, then filter after that:
SELECT
pl.Id AS Id,
pl.Name AS Name,
f.[Url] AS PrimaryImageUrl,
up.Id AS MemberId,
up.ProfessionalName,up.
AvatarUrl,
v.test,
TotalCount = COUNT(1) OVER()
FROM
dbo.Playlist pl
INNER JOIN
dbo.UserProfiles up ON pl.UserId = up.UserId
INNER JOIN
[dbo].[Files] AS f ON pl.[PrimaryImageId] = f.[Id]
CROSS APPLY (
SELECT test =
(SELECT
c.Id AS Id,
c.Name AS Name,
c.ContentImageUrl AS ImageUrl,
c.Price AS Price,
c.BPM AS BPM,
f.Id AS 'File.Id',
f.Url AS 'File.Name',
TotalCount = COUNT (c.Id) OVER()
FROM
dbo.Content c
INNER JOIN
dbo.PlayListContents pm ON c.Id = pm.ContentId
AND pm.PlaylistId = pl.Id
INNER JOIN
dbo.Files f ON c.ContentFileId = f.Id
FOR JSON PATH
)
) v
WHERE
(pl.Name LIKE '%' + #searchInput + '%')
AND v.test IS NOT NULL;
My proc looks like this :
Select pl.Id as Id,
pl.Name as Name,
f.[Url] as PrimaryImageUrl,
up.Id as MemberId,
up.ProfessionalName,
up.AvatarUrl,
(
select c.Id as Id,
c.Name as Name,
c.ContentImageUrl as ImageUrl,
c.Price as Price,
c.BPM as BPM,
f.Id as 'File.Id',
f.Url as 'File.Name',
g.Id as 'Genre.Id',
g.Name as 'Genre.Name',
kt.Id as 'KeyType.Id',
kt.Name as 'KeyType.Name',
tt.Id as 'TrackType.Id',
tt.Name as 'TrackType.Name',
TotalCount = count(c.Id) Over ()
from dbo.Content c
inner join dbo.PlayListContents pm
on c.Id = pm.ContentId
and pm.PlaylistId = pl.Id
inner join dbo.Files f
on c.ContentFileId = f.Id
inner join dbo.Genres g
on c.GenreTypeId = g.Id
inner join dbo.KeyType kt
on c.KeyTypeId = kt.Id
inner join dbo.TrackType tt
on tt.Id = c.TrackTypeId
Where (NOT EXISTS (
SELECT b.Bpm
FROM #Bpm AS b
WHERE b.Bpm IS NOT NULL)
OR c.Bpm IN (SELECT * FROM #Bpm)
)
for json path
) AS Content,
TotalCount = COUNT(1) OVER ()
from dbo.Playlist pl
inner join dbo.UserProfiles up
on pl.UserId = up.UserId
inner join [dbo].[Files] as f
ON pl.[PrimaryImageId] = f.[Id]
where (pl.Name LIKE '%' + #searchInput + '%')
Using this proc I sometimes get results with Content column at NULL.
why can't I add WHERE Content IS NOT NULL and have my results come back with no rows with NULL at Content column?
Hi I am calling a select query in a select, in Snowflake. I am facing the error as INVALID IDENTIFIER AS ROWNUM, when I comment Rownum, I am facing the error as Unsupported Subquery type cant evaluted.
My requirement is converting the existing oracle query to SNowflake.
SELECT DISTINCT cust.Id AS Customer_Id
,nvl((
SELECT *
FROM (
SELECT to_char(cliterm.Quantity)
FROM ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
WHERE rownum = 1
), cli.Quantity) AS Quantity_Purchased
,nvl((
SELECT *
FROM (
SELECT cliterm.UsedQuantity
FROM ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
WHERE rownum = 1
), cli.UsedQuantity) AS Quantity_Used_To_Date
,nvl((
SELECT *
FROM (
SELECT cliterm.StartDate
FROM ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
WHERE rownum = 1
), cli.StartDate) AS sbscription_Term_Start_Date
,nvl((
SELECT *
FROM (
SELECT cliterm.EndDate
FROM ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY id DESC
)
WHERE rownum = 1
), cli.EndDate) AS sbscription_Term_End_Date
,nvl(to_char(cli.EndDate), (
CASE
WHEN (
cli.StartDate IS NOT NULL
AND con.InitialTerm > 0
)
THEN 'Auto Renewal'
ELSE ''
END
)) AS Contr_End_Date
FROM ContractLineItem cli
INNER JOIN Contract con ON cli.Contract_id = con.Id
INNER JOIN Customer cust ON con.Customer_id = cust.Id
INNER JOIN Organization org ON org.Customer_id = cust.Id
INNER JOIN Product prod ON cli.Product_id = prod.Id
INNER JOIN Producttype pt ON prod.ProductBrand_id = pt.Id
LEFT JOIN account acc ON cust.SAN = acc.acc__c
LEFT JOIN account acc1 ON acc.parentid = acc1.id
LEFT JOIN sbSCRIPTION sb ON sb.id = cli.sforceid
LEFT JOIN sbSCRIPTION pasb ON pasb.id = sb.srequired
LEFT JOIN scontract1 cntr ON cntr.contractnumber = con.ContNumber
LEFT JOIN user accowner ON acc.ownerid = accowner.id
LEFT JOIN user accsalesmanager ON accowner.managerid = accsalesmanager.id
LEFT JOIN (
SELECT f.accountid
,g.managerid
,max(g.NAME) CSM
,max(g.id) CSMID
FROM accountteammember f
JOIN user g ON f.userid = g.id
WHERE f.teammemberrole = 'AGM'
GROUP BY f.accountid
,g.managerid
) acccsm ON acccsm.accountid = acc.id
LEFT JOIN product2 prd ON prod.Code = prd.productcode
LEFT JOIN prdfam prod_fam ON prod_fam.product_family_desc = prd.Product_Family__c
)
WHERE Quantity_Purchased <> 0
);
How to convert the same to snowflake supported, as it should pick the quantity column based on rownum=1, if it is null, it should be replaced by some x.
Try and change your query to this (change WHERE rownum = 1 to limit 1 :
,nvl((
SELECT *
FROM (
SELECT to_char(cliterm.Quantity)
FROM ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
ORDER BY cli.id DESC
)
limit 1
The example SQL is missing a couple layers of SELECT * FROM ( as you have to unmatched paren at the end. But assuming you are selecting * so your WHERE Quantity_Purchased <> 0 this can be coverted to a QUALIFY and the layers can be skipped.
There are two main things, how to convert the SQL, and how to avoid the corrolated sub-query
firstly the three sub-select in the JOIN have the same pattern, so we will talk about the first one, WHERE rownum = 1 can been done via a limit 1 order via QUALIFY I prefer the latter.
SELECT to_char(cliterm.Quantity)
FROM ContractLineItemTerm cliterm
WHERE cliterm.ContractLineItem_id = cli.Id
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
AND cliterm.PriceRuleItem_id IS NULL
QUALIFY row_numumber() OVER (ORDER BY cli.id DESC) = 1
then as you use this in the corrolated sub-query, which is actually also random, because you are ordering by cli.id but also joining on that same clause, so you in effect are not sorting your data. So firstly you need to have a better clause for selecting from ContractLineItemTerm I am going to make up a column called is_best just so the SQL makes sense, and then you can put something in there that, makes sense.
The next thing to note is your four selects are all the same SQL block, so we can change this to one join and be done with it.
so I have used a CTE just so you can see how the fours blocks where written as one, and reformatted your JOIN ON's to be on new lines, as for more complex SQL it is nicer, and I rewrote your CASE to be an IFF as it is a simple two branch case.
WITH best_per_id (
SELECT cliterm.ContractLineItem_id
,to_char(cliterm.Quantity) as Quantity
,cliterm.UsedQuantity
,cliterm.StartDate
FROM ContractLineItemTerm cliterm
WHERE cliterm.PriceRuleItem_id IS NULL
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
QUALIFY row_numumber() OVER (PARTITION BY cliterm.ContractLineItem_id
ORDER BY cliterm.is_best ) = 1
)
SELECT DISTINCT cust.Id AS Customer_Id
,nvl(bpi.Quantity, cli.Quantity) AS Quantity_Purchased
,nvl(bpi.UsedQuantity, cli.UsedQuantity) AS Quantity_Used_To_Date
,nvl(bpi.StartDate, cli.StartDate) AS sbscription_Term_Start_Date
,nvl(bpi.EndDate, cli.EndDate) AS sbscription_Term_End_Date
,nvl(to_char(cli.EndDate),
IFF(cli.StartDate IS NOT NULL AND con.InitialTerm > 0, 'Auto Renewal', '')
) AS Contr_End_Date
FROM ContractLineItem cli
INNER JOIN Contract con
ON cli.Contract_id = con.Id
INNER JOIN Customer cust
ON con.Customer_id = cust.Id
INNER JOIN Organization org
ON org.Customer_id = cust.Id
INNER JOIN Product prod
ON cli.Product_id = prod.Id
INNER JOIN Producttype pt
ON prod.ProductBrand_id = pt.Id
LEFT JOIN best_per_id as bpi
ON cli.id = bpi.ContractLineItem_id
LEFT JOIN account acc
ON cust.SAN = acc.acc__c
LEFT JOIN account acc1
ON acc.parentid = acc1.id
LEFT JOIN sbSCRIPTION sb
ON sb.id = cli.sforceid
LEFT JOIN sbSCRIPTION pasb
ON pasb.id = sb.srequired
LEFT JOIN scontract1 cntr
ON cntr.contractnumber = con.ContNumber
LEFT JOIN user accowner
ON acc.ownerid = accowner.id
LEFT JOIN user accsalesmanager
ON accowner.managerid = accsalesmanager.id
LEFT JOIN (
SELECT f.accountid
,g.managerid
,max(g.NAME) CSM
,max(g.id) CSMID
FROM accountteammember f
JOIN user g ON f.userid = g.id
WHERE f.teammemberrole = 'AGM'
GROUP BY f.accountid
,g.managerid
) acccsm ON acccsm.accountid = acc.id
LEFT JOIN product2 prd
ON prod.Code = prd.productcode
LEFT JOIN prdfam prod_fam
ON prod_fam.product_family_desc = prd.Product_Family__c
QUALIFY Quantity_Purchased <> 0;
but that can all be written as a subselect like is done with acccsm like so:
WITH best_per_id (
SELECT cliterm.ContractLineItem_id
,to_char(cliterm.Quantity) as Quantity
,cliterm.UsedQuantity
,cliterm.StartDate
FROM ContractLineItemTerm cliterm
WHERE cliterm.PriceRuleItem_id IS NULL
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
QUALIFY row_numumber() OVER (PARTITION BY cliterm.ContractLineItem_id
ORDER BY cliterm.is_best ) = 1
)
SELECT DISTINCT cust.Id AS Customer_Id
,nvl(bpi.Quantity, cli.Quantity) AS Quantity_Purchased
,nvl(bpi.UsedQuantity, cli.UsedQuantity) AS Quantity_Used_To_Date
,nvl(bpi.StartDate, cli.StartDate) AS sbscription_Term_Start_Date
,nvl(bpi.EndDate, cli.EndDate) AS sbscription_Term_End_Date
,nvl(to_char(cli.EndDate),
IFF(cli.StartDate IS NOT NULL AND con.InitialTerm > 0, 'Auto Renewal', '')
) AS Contr_End_Date
FROM ContractLineItem cli
INNER JOIN Contract con
ON cli.Contract_id = con.Id
INNER JOIN Customer cust
ON con.Customer_id = cust.Id
INNER JOIN Organization org
ON org.Customer_id = cust.Id
INNER JOIN Product prod
ON cli.Product_id = prod.Id
INNER JOIN Producttype pt
ON prod.ProductBrand_id = pt.Id
LEFT JOIN (
SELECT cliterm.ContractLineItem_id
,to_char(cliterm.Quantity) as Quantity
,cliterm.UsedQuantity
,cliterm.StartDate
FROM ContractLineItemTerm cliterm
WHERE cliterm.PriceRuleItem_id IS NULL
AND (
cliterm.EndDate IS NULL
OR cliterm.EndDate > add_months(sysdate, - 3)
)
QUALIFY row_numumber() OVER (PARTITION BY cliterm.ContractLineItem_id ORDER BY cliterm.is_best ) = 1
) as bpi
ON cli.id = bpi.ContractLineItem_id
LEFT JOIN account acc
ON cust.SAN = acc.acc__c
LEFT JOIN account acc1
ON acc.parentid = acc1.id
LEFT JOIN sbSCRIPTION sb
ON sb.id = cli.sforceid
LEFT JOIN sbSCRIPTION pasb
ON pasb.id = sb.srequired
LEFT JOIN scontract1 cntr
ON cntr.contractnumber = con.ContNumber
LEFT JOIN user accowner
ON acc.ownerid = accowner.id
LEFT JOIN user accsalesmanager
ON accowner.managerid = accsalesmanager.id
LEFT JOIN (
SELECT f.accountid
,g.managerid
,max(g.NAME) CSM
,max(g.id) CSMID
FROM accountteammember f
JOIN user g ON f.userid = g.id
WHERE f.teammemberrole = 'AGM'
GROUP BY f.accountid
,g.managerid
) acccsm ON acccsm.accountid = acc.id
LEFT JOIN product2 prd
ON prod.Code = prd.productcode
LEFT JOIN prdfam prod_fam
ON prod_fam.product_family_desc = prd.Product_Family__c
QUALIFY Quantity_Purchased <> 0;
I'm trying to create a CTE statement:
WITH StartCash (StartCash) AS
(
SELECT StartCash
FROM CashierInfo
WHERE CashierID = (SELECT MAX( CashierID)
FROM CashierInfo
WHERE UserID = 1 AND EndDate IS NULL)
)
SELECT
StartCash, a.username AS Username, b.Adress AS Adress,
(SUM(c.quantity * c.discountprice)) AS SumPrice,
c.Printed AS Printed, c.CashierUserID AS CashierUserID,
c.RetailDelivery AS RetailDelivery, c.TrnDocumentID
FROM
Users a
JOIN
InventoryTransTemp c ON c.CashierUserID = a.UserID
JOIN
DeliveryAdress b ON b.DeliveryAdressID = c.DeliveryAdressID
WHERE
c.cashieruserid = 1
GROUP BY
a.Username, b.Adress, c.Printed,
c.CashierUserID, c.RetailDelivery, c.TrnDocumentID
But I am getting an error
Invalid column name 'StartCash'
StartCash does not exist because your CTE is not included in your FROM clause.
Based solely on what I can see in your question, I assume it would be safe to JOIN CashierInfo.UserID to Users.UserID.
So try something like this:
WITH StartCash
AS (
SELECT StartCash
,UserID
FROM CashierInfo
WHERE CashierID = (
SELECT MAX(CashierID)
FROM CashierInfo
WHERE UserID = 1
AND EndDate IS NULL
)
)
SELECT sc.StartCash
,a.username AS Username
,b.Adress AS Adress
,(SUM(c.quantity * c.discountprice)) AS SumPrice
,c.Printed AS Printed
,c.CashierUserID AS CashierUserID
,c.RetailDelivery AS RetailDelivery
,c.TrnDocumentID
FROM StartCash sc
INNER JOIN Users a ON sc.UserID = a.UserID
INNER JOIN InventoryTransTemp c ON c.CashierUserID = a.UserID
INNER JOIN DeliveryAdress b ON b.DeliveryAdressID = c.DeliveryAdressID
WHERE c.cashieruserid = 1
GROUP BY sc.StartCash
,a.Username
,b.Adress
,c.Printed
,c.CashierUserID
,c.RetailDelivery
,c.TrnDocumentID
You do not have the CTE in the from clause. You need to join to the CTE but your CTE has only a summary value. https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017
Please help me to tune this sql server query. Here vcompanyquicksearch is a view on the company table.
What indexes should I create? A sort operation is taking place in the execution plan
which costs 24% i.e.,
[CCEP_DEV].[dbo].[Company].vchContactFirstName Descending,
[CCEP_DEV].[dbo].[Company].iCompanyId Ascending
I don't know why the second sorting is taking place... can anyone suggest why?
select top *
from vCompanyquicksearch
LEFT OUTER JOIN ReferenceParameters r1
on vCompanyquicksearch.iCompanyTypeCode = r1.iParameterId AND
r1.iSiteId =1
LEFT OUTER JOIN ReferenceParameters r2
on vCompanyquicksearch.iCompanySubTypeCode = r2.iParameterId AND
r2.iSiteId =1
LEFT OUTER JOIN ReferenceParameters r3
on vCompanyquicksearch.iPhoneTypeId = r3.iParameterId AND
r3.iSiteId =1
LEFT OUTER JOIN Country c ON
vCompanyquicksearch.chCountryCode = c.chCountryCode AND
ISNULL(vCompanyquicksearch.chCountryCode,'''') <> '''' and
c.iSiteId = 1
LEFT OUTER JOIN Region r ON
vCompanyquicksearch.chCountryCode = r.chCountryCode AND
ISNULL(vCompanyquicksearch.chCountryCode,'''') <> '''' AND
vCompanyquicksearch.chRegionCode = r.chRegionCode AND
ISNULL(vCompanyquicksearch.chRegionCode,'''') <> '''' and
r.iSiteId = 1
where vCompanyquicksearch.isiteid = 1 and vCompanyquicksearch.tirecordstatus = 1 and vCompanyquicksearch.iCompanyId in (
select distinct * from (
select customer_id from csu_customer_policy
inner join csu_policy on csu_policy.policy_number = csu_customer_policy.policy_number
and csu_policy.data_source = csu_customer_policy.data_source
where csu_policy.vehicle_no in(
'sgv3976r')
and csu_customer_policy.delete_status = 0 and csu_customer_policy.site_id = ' 1 '
) yTable
) Order by vchName desc
Try this one -
;WITH cte AS
(
SELECT *
FROM ReferenceParameters r
WHERE r.iSiteId = 1
)
SELECT /*TOP*/ *
FROM (
SELECT *
FROM dbo.vCompanyquicksearch c1 --<-- I think the main problem in this view
WHERE c1.isiteid = 1
AND c1.tirecordstatus = 1
) c1
LEFT JOIN cte r1 ON c1.iCompanyTypeCode = r1.iParameterId
LEFT JOIN cte r2 ON c1.iCompanySubTypeCode = r2.iParameterId
LEFT JOIN cte r3 ON c1.iPhoneTypeId = r3.iParameterId
LEFT JOIN (
SELECT *
FROM dbo.Country c
WHERE c.iSiteId = 1
) c ON c1.chCountryCode = c.chCountryCode
AND ISNULL(c1.chCountryCode, '') != ''
LEFT JOIN (
SELECT *
FROM dbo.Region r
WHERE r.iSiteId = 1
) r ON c1.chCountryCode = r.chCountryCode
AND c1.chRegionCode = r.chRegionCode
AND ISNULL(c1.chCountryCode, '') != ''
AND ISNULL(c1.chRegionCode,'') != ''
WHERE c1.iCompanyId IN
(
SELECT DISTINCT customer_id
FROM dbo.csu_customer_policy p
JOIN dbo.csu_policy pc ON pc.policy_number = p.policy_number
AND pc.data_source = p.data_source
WHERE pc.vehicle_no = 'sgv3976r'
AND p.delete_status = 0
AND p.site_id = ' 1 '
)
ORDER BY vchName DESC
Update:
...
SELECT *
FROM (
SELECT TOP ... *
FROM dbo.vCompanyquicksearch c1
WHERE c1.isiteid = 1
AND c1.tirecordstatus = 1
ORDER BY vchName DESC
) c1
...
WHERE c1.iCompanyId IN
(
SELECT DISTINCT customer_id
FROM dbo.csu_customer_policy p
JOIN dbo.csu_policy pc ON pc.policy_number = p.policy_number
AND pc.data_source = p.data_source
WHERE pc.vehicle_no = 'sgv3976r'
AND p.delete_status = 0
AND p.site_id = ' 1 '
)