Differences between equal sign(=) and IN with subquery - sql-server

I have a query it takes 20 seconds to execute, follow my query:
SELECT MATLIGA.COD_MAT_FAMILIA
FROM
ORCAMENTOS.dbo.OR_1INSUMOS INSUMOS
INNER JOIN ORCAMENTOS.dbo.OR_MAT_GRUPOS GRUPOS ON (GRUPOS.EMPRESA='01' AND GRUPOS.FILIAL='01' AND GRUPOS.CODIGO_INTERNO = 'HOT' )
INNER JOIN ORCAMENTOS.dbo.OR_MATERIAIS MATER ON (MATER.EMPRESA='01' AND MATER.FILIAL='01' AND MATER.CODIGO_GRUPO=GRUPOS.ID AND MATER.ID = INSUMOS.COD_INSUMO_MATER )
INNER JOIN ORCAMENTOS.dbo.OR_MAT_LIGACAO MATLIGA ON (MATLIGA.EMPRESA='01' AND MATLIGA.FILIAL='01' AND MATLIGA.CODIGO_MATERIAL = INSUMOS.COD_INSUMO_MATER)
WHERE INSUMOS.EMPRESA='01' AND INSUMOS.FILIAL='01'
AND INSUMOS.COD_INSUMO_MATER IS NOT NULL
AND INSUMOS.NUMERO=10865812
AND INSUMOS.OPCAO_SIMULACAO=1
AND INSUMOS.CODIGO_MAQUINA = (SELECT COD_MAQ_PROPOSTA FROM ORCAMENTOS.dbo.OR_1SIMULACOES AS ORC WHERE ORC.NUMERO=10865812 AND ORC.OPCAO_SIMULACAO = 1 AND ORC.EMPRESA='01' AND ORC.FILIAL='01' )
AND INSUMOS.OPCAO_MAQUINA = (SELECT OPCAO_MAQUINA FROM ORCAMENTOS.dbo.OR_1SIMULACOES AS ORC WHERE ORC.NUMERO=10865812 AND ORC.OPCAO_SIMULACAO = 1 AND ORC.EMPRESA='01' AND ORC.FILIAL='01' )
GROUP BY MATLIGA.COD_MAT_FAMILIA
ORDER BY 1
In these two lines bellow, if I change the equal signal by (IN), ( = ALL ) or ( = ANY ) it reduces the costs to 1 second.
AND INSUMOS.CODIGO_MAQUINA IN (SELECT COD_MAQ_PROPOSTA FROM ORCAMENTOS.dbo.OR_1SIMULACOES AS ORC WHERE ORC.NUMERO=10865812 AND ORC.OPCAO_SIMULACAO = 1 AND ORC.EMPRESA='01' AND ORC.FILIAL='01' )
AND INSUMOS.OPCAO_MAQUINA IN (SELECT OPCAO_MAQUINA FROM ORCAMENTOS.dbo.OR_1SIMULACOES AS ORC WHERE ORC.NUMERO=10865812 AND ORC.OPCAO_SIMULACAO = 1 AND ORC.EMPRESA='01' AND ORC.FILIAL='01' )
Whats the difference between them?
Tks.

There is a small semantic difference. The first query must fail if the subquery matches more than one record. So it has to finish the subquery until the end:
where col1 = (select col1 from table2)
The second query can stop once it encounters a match:
where col1 in (select col1 from table2)

Related

How will SQL Server execute this WITH clause

I have the following query. Here 'B' is giving me non repeated MessageIds and i am using them in subquery with A, B is internally using A.
So when i call SELECT in the last part, will it execute A again or will it use data already fetched while B was being called ?
WITH A as (
SELECT z.Name, ze.Inside, ze.MessageId, ze.DateTime
FROM ZoneStateEntries ze
INNER JOIN Zone z
ON ze.ZoneId = z.ZoneId
WHERE ze.ObjectId = 1324
AND (Inside = 1 OR Inside = 0)
AND ze.DateTime BETWEEN '2018-10-22 00:00:00' AND '2019-11-05 00:00:00'
),
B as (
SELECT a.MessageId
FROM A a
INNER JOIN A b
on a.MessageId = b.MessageId
GROUP BY a.MessageId
HAVING COUNT(a.MessageId) = 1
)
SELECT *
FROM A
WHERE MessageId IN (
SELECT *
FROM B
)
AND a.Inside = 1
ORDER BY DateTime DESC
The data here is huge and we can't afford to execute query A multiple times. Can we optimize it further?
A a INNER JOIN A b looks like unnecessary. You can use COUNT(DISTINCT MessageId) for getting unique messages.
WITH A as (
SELECT z.Name, ze.Inside, ze.MessageId, ze.DateTime
FROM ZoneStateEntries ze
INNER JOIN Zone z
ON ze.ZoneId = z.ZoneId
WHERE ze.ObjectId = 1324
AND (Inside = 1 OR Inside = 0)
AND ze.DateTime BETWEEN '2018-10-22 00:00:00' AND '2019-11-05 00:00:00'
)
SELECT *
FROM A
WHERE MessageId IN (
SELECT MessageId
FROM A
GROUP BY MessageId
HAVING COUNT(DISTINCT MessageId) = 1
)
AND a.Inside = 1
ORDER BY DateTime DESC

Avoid table function in where clause?

I have added table function in the where clause.
select cmp_id, acno_code, sl_type, sl_code, 0 op_Dr, 0 op_cr, 0 tr_Dr, sum(amount) tr_Cr
from vf_finance
where cmp_id =#cmp_id1
and unitcode in (select * from UTILfn_Split( #unit_code,',') )
and stat_code in ('AT','PR' )
--and pc_code in (select * from UTILfn_Split( #sba,',') )
AND DOC_dT >=convert(datetime,#from_date,103) and doc_Dt <= convert(datetime,#to_date,103)
and amount < 0
GROUP BY cmp_id, acno_code, sl_type, sl_code
) as gl
inner join ps_Accmas acc on acc.cmp_id = gl.cmp_id and acc.acno_Code = gl.acno_code
inner join ps_owner o on gl.cmp_id = o.cmp_id
left outer join view_sl_code sl on gl.cmp_id = sl.cmp_id and gl.sl_type = sl.sl_type and gl.sl_Code = sl.sl_Code
inner join ps_slType slt on gl.cmp_id = slt.cmp_id and gl.sl_Type = slt.sl_type
where sl.sl_type in (select * from UTILfn_Split( #sl_type,',') )
and acc.acno_code in(select * from UTILfn_Split( #facno_code,',') )
group by gl.cmp_id, gl.acno_code,gl.sl_code,gl.sl_type,slt.sl_DEsc,acc.acno_DEsc, sl.sl_DEsc, o.owner_name
order by gl.cmp_id, gl.acno_code,gl.sl_code,gl.sl_type
Can anyone please suggest how I can avoid function in where clause?
You may try this. There are some issues in this existing query which I'll point first
First unitcode in (select * from UTILfn_Split( #unit_code,',') here you must use one column name instead of *, although i don't know about your function UTILfn_Split but still mention column name is preferable.
for your query you may use inner join instead of in with function having return type table.
Instead of
sl.sl_type in (select * from UTILfn_Split( #sl_type,',') )
You may try this
yourtble as sl inner join
(select value from UTILfn_Split( #sl_type,',') as t2
on sl.sl_type = t2.[value] ---- here column name with t2 depends on your function,
---what table structure is returning, in your case it is [value]

Update records SQL?

First when I started this project seemed very simple. Two tables, field tbl1_USERMASTERID in Table 1 should be update from field tbl2_USERMASTERID Table 2. After I looked deeply in Table 2, there is no unique ID that I can use as a key to join these two tables. Only way to match the records from Table 1 and Table 2 is based on FIRST_NAME, LAST_NAME AND DOB. So I have to find records in Table 1 where:
tbl1_FIRST_NAME equals tbl2_FIRST_NAME
AND
tbl1_LAST_NAME equals tbl2_LAST_NAME
AND
tbl1_DOB equals tbl2_DOB
and then update USERMASTERID field. I was afraid that this can cause some duplicates and some users will end up with USERMASTERID that does not belong to them. So if I find more than one record based on first,last name and dob those records would not be updated. I would like just to skip and leave them blank. That way I wouldn't populate invalid USERMASTERID. I'm not sure what is the best way to approach this problem, should I use SQL or ColdFusion (my server side language)? Also how to detect more than one matching record?
Here is what I have so far:
UPDATE Table1 AS tbl1
LEFT OUTER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.fname = tbl2.fname
AND tbl1.lname = tbl2.lname
SET tbl1.usermasterid = tbl2.usermasterid
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
Here is query where I tried to detect duplicates:
SELECT DISTINCT
tbl1.FName,
tbl1.LName,
tbl1.dob,
COUNT(*) AS count
FROM Table1 AS tbl1
LEFT OUTER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.FName = tbl2.first
AND tbl1.LName = tbl2.last
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
AND LTRIM(RTRIM(tbl1.first)) <> ''
AND LTRIM(RTRIM(tbl1.last)) <> ''
AND LTRIM(RTRIM(tbl1.dob)) <> ''
GROUP BY tbl1.FName,tbl1.LName,tbl1.dob
Some data after I tested query above:
First Last DOB Count
John Cook 2008-07-11 2
Kate Witt 2013-06-05 1
Deb Ruis 2016-01-22 1
Mike Bennet 2007-01-15 1
Kristy Cruz 1997-10-20 1
Colin Jones 2011-10-13 1
Kevin Smith 2010-02-24 1
Corey Bruce 2008-04-11 1
Shawn Maiers 2016-08-28 1
Alenn Fitchner 1998-05-17 1
If anyone have idea how I can prevent/skip updating duplicate records or how to improve this query please let me know. Thank you.
You could check for and avoid duplicate matches using with common_table_expression (Transact-SQL)
along with row_number()., like so:
with cte as (
select
t.fname
, t.lname
, t.dob
, t.usermasterid
, NewUserMasterId = t2.usermasterid
, rn = row_number() over (partition by t.fname, t.lname, t.dob order by t2.usermasterid)
from table1 as t
inner join table2 as t2 on t.dob = t2.dob
and t.fname = t2.fname
and t.lname = t2.lname
and ltrim(rtrim(t.usermasterid)) = ''
)
--/* confirm these are the rows you want updated
select *
from cte as t
where t.NewUserMasterId != ''
and not exists (
select 1
from cte as i
where t.dob = i.dob
and t.fname = i.fname
and t.lname = i.lname
and i.rn>1
);
--*/
/* update those where only 1 usermasterid matches this record
update t
set t.usermasterid = t.NewUserMasterId
from cte as t
where t.NewUserMasterId != ''
and not exists (
select 1
from cte as i
where t.dob = i.dob
and t.fname = i.fname
and t.lname = i.lname
and i.rn>1
);
--*/
I use the cte to extract out the sub query for readability. Per the documentation, a common table expression (cte):
Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement.
Using row_number() to assign a number for each row, starting at 1 for each partition of t.fname, t.lname, t.dob. Having those numbered allows us to check for the existence of duplicates with the not exists() clause with ... and i.rn>1
You could use a CTE to filter out the duplicates from Table1 before joining:
; with CTE as (select *
, count(ID) over (partition by LastName, FirstName, DoB) as IDs
from Table1)
update a
set a.ID = b.ID
from Table2 a
left join CTE b
on a.FirstName = b.FirstName
and a.LastName = b.LastName
and a.Dob = b.Dob
and b.IDs = 1
This will work provided there are no exact duplicates (same demographics and same ID) in table 1. If there are exact duplicates, they will also be excluded from the join, but you can filter them out before the CTE to avoid this.
Please try below SQL:
UPDATE Table1 AS tbl1
INNER JOIN Table2 AS tbl2
ON tbl1.dob = tbl2.dob
AND tbl1.fname = tbl2.fname
AND tbl1.lname = tbl2.lname
LEFT JOIN Table2 AS tbl3
ON tbl3.dob = tbl2.dob
AND tbl3.fname = tbl2.fname
AND tbl3.lname = tbl2.lname
AND tbl3.usermasterid <> tbl2.usermasterid
SET tbl1.usermasterid = tbl2.usermasterid
WHERE LTRIM(RTRIM(tbl1.usermasterid)) = ''
AND tbl3.usermasterid is null

How can I get result from group by on With clause(cte) in tsql

I use this query for get these result :
code:
With Res
As
(
SELECT GroupID ,HV.[HadithVerID] As HadithId ,CenturyID
FROM JHadithVer HV
INNER JOIN JHadith H ON HV.HadithID = H.HadithID
WHERE HV.SourceID=28
)
Select * From Res
Result:
GroupId Hadithid CenturyId
7565 27062 4
22206 27063 4
125903 27064 6
60671 27065 4
125903 27074 4
125903 27083 4
How can I change my select of with(Res) for get HadithId that between common GroupId with less CenturyId. For example between
125903 27064 6
and
125903 27074 4
and
125903 27083 4
result is : 27074(Between 2 result 27074 & 27083, I want 27074 that is less!)
I think this can help you.
With Res
As
(
SELECT GroupID ,HV.[HadithVerID] As HadithId ,CenturyID
FROM JHadithVer HV
INNER JOIN JHadith H ON HV.HadithID = H.HadithID
WHERE HV.SourceID=28
)
Select GroupID ,MIN(HadithId),CenturyID
From Res
Group By GroupID,CenturyID
So, as I understand, you need to rank your records and then select one with minimal rank for example. Ranking should be done in the following way: minimal rank for particular GroupId has record with minimal Hadithid for minimal CenturyId. You need only rank your records in CTE expression using ranking function ROW_NUMBER():
With Res
As
(
SELECT GroupID ,HV.[HadithVerID] As HadithId ,CenturyID,
-- Add ranking
ROW_NUMBER() OVER(PARTITION BY GroupId ORDER BY CenturyId, HadthId) AS RANK
FROM JHadithVer HV
INNER JOIN JHadith H ON HV.HadithID = H.HadithID
WHERE HV.SourceID=28
)
Select * From Res
WHERE RANK = 1 -- select all minimal values for every GroupId
You just query your CTE result set like this:
SELECT
T.GroupID,
T.Hadithid,
T.CenturyID
FROM RES T
INNER JOIN (
SELECT
T.GroupId,
T.CenturyID,
MIN(T.Hadithid) AS 'Hadithid'
FROM RES T
INNER JOIN (
SELECT
GroupID,
MIN(CenturyID) AS 'CenturyID'
FROM RES T
GROUP BY GroupID
) T3 ON T3.CenturyID = T.CenturyID
GROUP BY T.GroupID, T.CenturyID
)
T2 ON T.Hadithid = T2.Hadithid
WHERE T.GROUPID = 125903
Here is a SQLFiddle.

Sub query in Store Procedure

I have a query in sql stored procedure. I want to get record from other query from its id how I do that.
SELECT t.Name ,t.CreatedDate ,t.CreatedBy , t.Amount
,t.Margin ,t.Probability ,t.Id
FROM (SELECT a = 1) a
CROSS JOIN
(SELECT
Name = HirschInternational_MSCRM.dbo.SalesOrderBase.Name
,CreatedDate=HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedOn
,CreatedBy=HirschInternational_MSCRM.dbo.SystemUserBase.FullName
,Amount = totalamount
,Probability=CloseProbability
,Id=SalesOrderId
,Margin=(SELECT ( ISNULL( ((Sum(Price)-Sum(CurrentCost)) / NULLIF( Sum(Price), 0 ))*100, 0 ) )
FROM HirschInternational_MSCRM.dbo.ProductBase
JOIN HirschInternational_MSCRM.dbo.SalesOrderDetailBase
ON HirschInternational_MSCRM.dbo.SalesOrderDetailBase.ProductId = HirschInternational_MSCRM.dbo.ProductBase.ProductId
JOIN HirschInternational_MSCRM.dbo.SalesOrderBase
ON HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId = HirschInternational_MSCRM.dbo.SalesOrderDetailBase.SalesOrderId)
FROM HirschInternational_MSCRM.dbo.SalesOrderBase
JOIN HirschInternational_MSCRM.dbo.OpportunityBase
ON HirschInternational_MSCRM.dbo.SalesOrderBase.Opportunityid = HirschInternational_MSCRM.dbo.OpportunityBase.Opportunityid
JOIN HirschInternational_MSCRM.dbo.SystemUserBase
ON HirschInternational_MSCRM.dbo.SystemUserBase.SystemUserId = HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedBy
WHERE YEAR(HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedOn)=YEAR(GETDATE())
I want Margin from every record I want Output like
It's not entirely clear what you want, but you might be looking for something like
select *
from (your SQL SELECT statement goes here) t1
where id = ?;
I want to get margin of every record how I filter margin query for SalesOrderId
like
Margin=(SELECT ( ISNULL( ((Sum(Price)-Sum(CurrentCost)) / NULLIF( Sum(Price), 0 ))*100, 0 ) )
FROM HirschInternational_MSCRM.dbo.ProductBase
JOIN HirschInternational_MSCRM.dbo.SalesOrderDetailBase
ON HirschInternational_MSCRM.dbo.SalesOrderDetailBase.ProductId = HirschInternational_MSCRM.dbo.ProductBase.ProductId
JOIN HirschInternational_MSCRM.dbo.SalesOrderBase
ON HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId = HirschInternational_MSCRM.dbo.SalesOrderDetailBase.SalesOrderId
Where HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId= //SalesOrderId that I get in main query)
how I pass that SalesOrderId in this query

Resources