Convert from stored procedure to SQL Query - sql-server

I want a SQL query for the third procedure
Convert this stored procedure to a SQL query :
CREATE PROC [WaterlilyT].[uisp_Rep_HRClearance_RND]
(
#pnCompCode DECIMAL(18,0)=0,
#pnClearanceNo VARCHAR(5000)='',
#AsonDate varchar(20)='1900-01-01'
)
AS
BEGIN
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb..#TempHRCLNos') IS NOT NULL
DROP TABLE #TempHRCLNos
SELECT CAST(val AS Decimal(18,0)) clslno
INTO #TempHRCLNos
FROM dbo.split(#pnClearanceNo,',')
CREATE NONCLUSTERED INDEX ix_TempHRCLslno ON #TempHRCLNos(clslno)
DECLARE #pnVisaReq decimal
SET #pnVisaReq = 0
DECLARE #ldAsonDate Date
SET #ldAsonDate = CONVERT(DATETIME, AsonDate, 103)
--if OBJECT_ID('tempdb..#TempHRCLVisaReq') is not null drop table #TempHRCLVisaReq
if OBJECT_ID('tempdb..#TempHRCLJoining') is not null drop table #TempHRCLJoining
SELECT c.serialno,d.posiref posname,d.gender,count(a.serialno) visareq,count(b.serialno) visarefused,count(e.serialno) visarec
Into #TempHRCLVisaReq
FROM [WaterlilyT].[vtwfhclearance] c
Join [WaterlilyT].[vtwfhvisaprocreq] a on a.clearno = c.serialno
join waterlilyt.vtwfhofferletter ofr on ofr.serialno = a.offrefno
join waterlilyt.vtwfhresbnk res on res.serialno = ofr.candcode
join [WaterlilyT].[vtwfdpclearance] d on d.serialno = c.serialno and d.gender = res.gender
left join [WaterlilyT].[vtwfhvisaprociss] b on b.visareq = a.serialno and b.visastat = 20
left join [WaterlilyT].[vtwfhvisaprociss] e on e.visareq = a.serialno and e.visastat = 10
where isnull(a.appstat,0) = 50
and (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = a.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=a.clearno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and c.clearpdt < Dateadd(day,1,#ldAsonDate) ) )
Group by c.serialno,d.posiref,d.gender
SELECT c.serialno,e.codeval desg,f.gender gendercode ,count(jp.serialno) joincnt
Into #TempHRCLJoining
FROM WaterlilyT.vtwfhjoinprocess jp
join waterlilyt.vtwfhresbnk f on f.serialno = jp.candcd
Join [WaterlilyT].[vtwfhvisaprocreq] vreq on jp.offerno = isnull(vreq.offrefno,0)
Join [WaterlilyT].[vtwfhclearance] c on vreq.clearno = c.serialno
--Join UlexM.vmunmglobal e on isnull(e.serialno,'') = vreq.posname and gtype = 'DESIG' and isactive = 1 and islstlvl = 1
--Join [WaterlilyT].[vtwfdpclearance] d on d.serialno = c.serialno and d.posiref = isnull(e.strvalue,0) and d.gender = f.gender
join Ulexm.vmundgeneral e on e.mastcd = 'CLRPOS' and e.codeval = vreq.posname
Join [WaterlilyT].[vtwfdpclearance] d on d.serialno = c.serialno and d.posiref = isnull(e.codeval,0) and d.gender = f.gender
where isnull(jp.appstat,0) =50 and jp.jointyp <> 10 and isnull(vreq.appstat,0) = 50
and (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = jp.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=vreq.clearno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and c.clearpdt < Dateadd(day,1,#ldAsonDate)) )
Group by c.serialno,e.codeval,f.gender
/*SELECT hc.serialno,SlNo,ClearanceNo,Convert(Varchar(10),Clearancedate,103) Clearancedate,Positioncode,PositionName,
hc.Gender,isnull(TotalNumber,0) TotalNumber,validityDate,
Case When validityDate >= Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end then
DATEDIFF(DAY,Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end,validityDate) Else 0 End DaysToGo,
--isnull(vreq.visareq,0) [VisaRequested],
isnull(req.visareq,0) [VisaRequested],
isnull(req.visarefused,0) RefusedByROP ,isnull(req.visareq,0)-isnull(req.visarefused,0) [VisaRecd],isnull(jp.joincnt,0) Joined,
(isnull(req.visareq,0)-isnull(req.visarefused,0)) - isnull(jp.joincnt,0) EmpYetToJoin,VisaExpired,
isnull(TotalNumber,0) - (isnull(req.visareq,0) + isnull(req.visarefused,0) + VisaExpired ) Pending
FROM WaterlilyT.vinforClearance hc
--left Join #TempHRCLVisaReq vreq on hc.serialno =vreq.serialno and hc.desg = vreq.desg
--Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.desg =jp.desg
Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.PositionCode =jp.desg and jp.gendercode = hc.gendercode
Left Join #TempHRCLVisaReq req on req.serialno = hc.serialno and req.posname = hc.PositionCode and req.gender = hc.gendercode
where (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = hc.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=hc.serialno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and Clearancedate < Dateadd(day,1,#ldAsonDate) ) )*/
SELECT hc.serialno,SlNo,ClearanceNo,Convert(Varchar(10),Clearancedate,103) Clearancedate,Positioncode,PositionName,
hc.Gender,isnull(TotalNumber,0) TotalNumber,validityDate,
Case When validityDate >= Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end then
DATEDIFF(DAY,Case when #ldAsonDate ='1900-01-01' then getdate() else #ldAsonDate end,validityDate) Else 0 End DaysToGo,
isnull(req.visareq,0) [VisaRequested],
isnull(req.visarefused,0) RefusedByROP ,isnull(req.visarec,0) [VisaRecd],isnull(jp.joincnt,0) Joined,
isnull(req.visarec,0) - isnull(jp.joincnt,0) EmpYetToJoin,VisaExpired,
isnull(TotalNumber,0) - (isnull(req.visareq,0) + isnull(req.visarefused,0) + VisaExpired ) Pending
FROM WaterlilyT.vinforClearance hc
--left Join #TempHRCLVisaReq vreq on hc.serialno =vreq.serialno and hc.desg = vreq.desg
--Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.desg =jp.desg
Left Join #TempHRCLJoining jp on hc.serialno =jp.serialno and hc.PositionCode =jp.desg and jp.gendercode = hc.gendercode
Left Join #TempHRCLVisaReq req on req.serialno = hc.serialno and req.posname = hc.PositionCode and req.gender = hc.gendercode
where (#pnCompCode =0 or (#pnCompCode !=0 and #pnCompCode = hc.bcd))
and (#pnClearanceNo ='' or (#pnClearanceNo != '' and exists (select 1 from #TempHRCLNos where clslno=hc.serialno)))
and (#ldAsonDate = '1900-01-01' or (#ldAsonDate <> '1900-01-01' and Clearancedate < Dateadd(day,1,#ldAsonDate) ) )
END

Related

SQL select unique column with maximum for 2nd column

Please how to combine maximum and distinct to have always unique Id and maximum of the column for that unique Id?
For example, if I have,
OrdinaceId Priloha2Id
5 1
5 2
6 2
6 4
7 1
result will be
OrdinaceId Priloha2Id
5 2
6 4
7 1
how to return only 1 row(with the same Id) with a maximum of Priloha2Id?
select * from (select
distinct ord.Id as OrdinaceId,
ord.CleneniPzsId,
posk.Id,
posk.ICO as Ico,
zar.ICZ as Icz,
posk.NazevZkraceny as Zkratka,
case when cle.Primariat = 0 then cle.Icp end as Icp,
IIF(cle.Primariat = 1, pri.OborKod , cle.OdbornostKod) as OdbornostKod,
ord.Nazev as OrdinaceNazev,
(select Street + N' ' + DescriptiveNo + N', ' + PostCode + N' ' + City from ICIS_Repl.repl.Address where Code = ord.NavAddressCode and Type = N'ORDINACE' and (ValidFrom is null or ValidFrom <= GETDATE()) and (ValidTill is null or ValidTill >= GETDATE() or ValidTill = N'1753-01-01 00:00:00')) as OrdinaceAdresaCela,
pril.Id as Priloha2Id,
cle.Smluvni,
cisP2KomunikaceStav.Nazev as EP2,
cisPzs.Nazev as StavPzp,
pril.Status,
pril.Info,
pril.PriPlatnostOd as PlatnostOd,
pril.PriPlatnostDo as PlatnostDo
from Ordinace ord
left join CleneniPzs cle on cle.Id = ord.CleneniPzsId
left join ZarizeniPZS zar on cle.ZarizeniPzsId = zar.Id
left join PoskytovatelZS posk on zar.PoskytovatelZsId = posk.Id
left join Primariat pri on cle.PrimariatId = pri.Id
left join Pril2Formular pr on pr.CleneniPzsId = cle.Id
left join Priloha2 pril on pril.Id = pr.Priloha2Id and (pril.PriPlatnostOd <= GETDATE() or pril.PriPlatnostOd is null) and (pril.PriPlatnostDo is null or pril.PriPlatnostDo >= GETDATE())
join CisCiselnik cisP2KomunikaceStav on posk.P2KomunikaceStavKod = cisP2KomunikaceStav.Kod AND cisP2KomunikaceStav.Oblast = N'P2KomunikaceStav' and cisP2KomunikaceStav.PlatnostOd <= GETDATE() and (cisP2KomunikaceStav.PlatnostDo is null or cisP2KomunikaceStav.PlatnostDo >= GETDATE())
left join P2Formular form on form.Icp = cle.Icp and form.Aktivni = 1
left join CisCiselnik cisPzs on form.P2StavPzpKod = cisPzs.Kod AND cisPzs.Oblast = N'P2StavPZP' and cisPzs.PlatnostOd <= GETDATE() and (cisPzs.PlatnostDo is null or cisPzs.PlatnostDo >= GETDATE())
left join P2ZarizeniPZS z on form.P2ZarizeniPzsId = z.Id and z.Icz = zar.ICZ and z.PoskytovatelZsId = posk.Id
join Smlouva smlv on smlv.Id = pril.SmlouvaId
left join SmluvniVykon smlVyk on smlVyk.CleneniPzsId = cle.Id and smlVyk.PlatnostOd <= GETDATE() and (smlVyk.PlatnostDo is null or smlVyk.PlatnostDo >= GETDATE())
left join SmlVykonVyjadreniRL vyjadreni on vyjadreni.Id = smlVyk.VyjadreniRLId ) a
You may use CTE to get max(Priloha2Id) per id. Then join to it.
Something like:
;with Pril2Formular_max_per_id as (
select ord.Id as OrdinaceId, max(pr.Priloha2Id) as max_Priloha2Id
from Ordinace ord
left join CleneniPzs cle on cle.Id = ord.CleneniPzsId
left join Pril2Formular pr on pr.CleneniPzsId = cle.Id
group by ord.Id
)
select * from (select
distinct ord.Id as OrdinaceId,[![enter image description here][1]][1]
ord.CleneniPzsId,
posk.Id,
posk.ICO as Ico,
zar.ICZ as Icz,
posk.NazevZkraceny as Zkratka,
case when cle.Primariat = 0 then cle.Icp end as Icp,
IIF(cle.Primariat = 1, pri.OborKod , cle.OdbornostKod) as OdbornostKod,
ord.Nazev as OrdinaceNazev,
(select Street + N' ' + DescriptiveNo + N', ' + PostCode + N' ' + City from ICIS_Repl.repl.Address where Code = ord.NavAddressCode and Type = N'ORDINACE' and (ValidFrom is null or ValidFrom <= GETDATE()) and (ValidTill is null or ValidTill >= GETDATE() or ValidTill = N'1753-01-01 00:00:00')) as OrdinaceAdresaCela,
pril.Id as Priloha2Id,
cle.Smluvni,
cisP2KomunikaceStav.Nazev as EP2,
cisPzs.Nazev as StavPzp,
pril.Status,
pril.Info,
pril.PriPlatnostOd as PlatnostOd,
pril.PriPlatnostDo as PlatnostDo
from Ordinace ord
left join CleneniPzs cle on cle.Id = ord.CleneniPzsId
left join ZarizeniPZS zar on cle.ZarizeniPzsId = zar.Id
left join PoskytovatelZS posk on zar.PoskytovatelZsId = posk.Id
left join Primariat pri on cle.PrimariatId = pri.Id
left join Pril2Formular_max_per_id pr on pr.OrdinaceId = ord.Id
left join Priloha2 pril on pril.Id = pr.max_Priloha2Id and (pril.PriPlatnostOd <= GETDATE() or pril.PriPlatnostOd is null) and (pril.PriPlatnostDo is null or pril.PriPlatnostDo >= GETDATE())
join CisCiselnik cisP2KomunikaceStav on posk.P2KomunikaceStavKod = cisP2KomunikaceStav.Kod AND cisP2KomunikaceStav.Oblast = N'P2KomunikaceStav' and cisP2KomunikaceStav.PlatnostOd <= GETDATE() and (cisP2KomunikaceStav.PlatnostDo is null or cisP2KomunikaceStav.PlatnostDo >= GETDATE())
left join P2Formular form on form.Icp = cle.Icp and form.Aktivni = 1
left join CisCiselnik cisPzs on form.P2StavPzpKod = cisPzs.Kod AND cisPzs.Oblast = N'P2StavPZP' and cisPzs.PlatnostOd <= GETDATE() and (cisPzs.PlatnostDo is null or cisPzs.PlatnostDo >= GETDATE())
left join P2ZarizeniPZS z on form.P2ZarizeniPzsId = z.Id and z.Icz = zar.ICZ and z.PoskytovatelZsId = posk.Id
join Smlouva smlv on smlv.Id = pril.SmlouvaId
left join SmluvniVykon smlVyk on smlVyk.CleneniPzsId = cle.Id and smlVyk.PlatnostOd <= GETDATE() and (smlVyk.PlatnostDo is null or smlVyk.PlatnostDo >= GETDATE())
left join SmlVykonVyjadreniRL vyjadreni on vyjadreni.Id = smlVyk.VyjadreniRLId ) a ;
select Id, max(Priloha2Id) from table group by Id

SQL INSERT statements

The first piece of code represents a update statement that updates all existing columns rows to whatever the user wants. So then i wrote a select statement that grabbed all the columns that were null/not existing and it returns 63 rows without the end where statement but with it then returns 62 which are the ones that are NULL not existing. So now I need to convert the sql select that selects all NUll rows into a insert than puts data into those not existing records. so far I posted what i have. Why isn't this working? it is saying that column schoolDay does not exist, how do i input those fields?
update e
set e.type = #dayEvent
from odb.dayEvent e
inner join odb.day d on e.dayID = d.dayID
inner join MMSD.vSchoolFromCalendar c on d.calendarID = c.calendarID
and d.structureID = c.structureID
inner join odb.PeriodSchedule p on d.periodScheduleID = p.periodScheduleID
and d.structureID = p.structureID
where d.[date] between #toDate and #fromDate
and datepart(dw, d.[date]) not in (1,7)
and e.[type] != #dayEvent
and DistrictCode = 'MA'
and FiscalYear = #FiscalYear
and summerSchool = '0'
and left(SchoolCode, 1) = #schoolChoice
and e.[type] != #dayEvent
select
sts = 'success',
result = convert(varchar, ##rowcount) + ' rows updated.';
set #rowcount = (select ##rowcount);
select
d.schoolDay,
d.instruction,
d.attendance,
d.duration,
d.comments,
d.startTime, d.endTime,
e.type
from
odb.dayEvent e
right outer join
odb.day d on e.dayID = d.dayID
inner join
MMSD.vSchoolFromCalendar c on d.calendarID = c.calendarID
and d.structureID = c.structureID
inner join
odb.PeriodSchedule p on d.periodScheduleID = p.periodScheduleID
and d.structureID = p.structureID
where
d.[date] between '2019-02-12' and '2019-02-12'
and datepart(dw, d.[date]) not in (1, 7)
and DistrictCode = 'MA'
and FiscalYear = '2019'
and summerSchool = '0'
and left(SchoolCode, 1) = '0'
and e.dayEventID IS NULL
Code so far
INSERT INTO odb.dayEvent (schoolDay, instruction, attendance, duration, comments, startTime, endTime)
SELECT
d.schoolDay, d.instruction, d.attendance, d.duration, d.comments,
d.startTime, d.endTime
FROM
odb.dayEvent e
RIGHT OUTER JOIN
odb.day d ON e.dayID = d.dayID
INNER JOIN
MMSD.vSchoolFromCalendar c ON d.calendarID = c.calendarID
AND d.structureID = c.structureID
INNER JOIN
odb.PeriodSchedule p ON d.periodScheduleID = p.periodScheduleID
AND d.structureID = p.structureID
WHERE
d.[date] BETWEEN '2019-02-12' AND '2019-02-12'
AND DATEPART(dw, d.[date]) NOT IN (1, 7)
AND DistrictCode = 'MA'
AND FiscalYear = '2019'
AND summerSchool = '0'
AND LEFT(SchoolCode, 1) = '0'
AND e.dayEventID IS NULL
This is my answer for now, looks like another peace of my code was already solving my questioning issue.....
insert into odb.DayEvent
(dayID, type, duration, instructionalMinutes)
select
e.dayID, e.type, e.duration, e.instructionalMinutes
from odb.dayEvent e
RIGHT OUTER JOIN odb.day d ON e.dayID = d.dayID
INNER JOIN MMSD.vSchoolFromCalendar c ON d.calendarID = c.calendarID
and d.structureID = c.structureID
INNER JOIN odb.PeriodSchedule p ON d.periodScheduleID = p.periodScheduleID
and d.structureID = p.structureID
WHERE d.[date] between '2019-02-12' and '2019-02-12'
and datepart(dw,d.[date]) not in (1,7)
and DistrictCode = 'MA'
and FiscalYear = '2019'
and summerSchool = '0'
and left(SchoolCode,1) = '0'
and e.type IS NULL
select sts='success', result= convert( varchar,##rowcount) + ' rows updated.';
set #rowcount = (select ##rowcount);

SQL Server 2014 - Multiple SUM/COUNT with subqueries

I have a two part question.
First part is about the speed of what I am doing below. I am taking a data set and getting each DISTINCT, then joining a subquery that sums/counts with criteria, then repeating that five times. After the first LEFT JOIN I have a run time of 02 seconds, after the second LEFT JOIN I have a run time of 04 seconds, but on the third LEFT JOIN my run time goes to 44 seconds. If that pull that query aside and run it alone, it is just 01 second. The total run time for the finished query is 70 seconds.
First part question:
What is making this query dramatically slower at the third join?
Second part: I am sure that I am accomplishing this in an inefficient way. I looked around for a while and was unable to find a way to accomplish what I am doing in a simple way while still being able to have different criteria for each subquery.
Second part question:
Is there a better way of accomplishing this query?
Edit after user1413's comment.
SELECT DISTINCT at the beginning was showing 49% cost in SQL Server execution plan view. I changed the table that the SELECT DISTINCT was selecting from and my run time went down to below 01 second.
SELECT DISTINCT
od.location, currentTires, currentAlignments, currentLubes,
currentBatteries,currentSiping,currentCarcount
FROM
comm.dbo.ordetail as od
LEFT JOIN
(SELECT
od2.location, SUM(od2.qty_shipped) as currentTires
FROM
comm.dbo.ordetail as od2
JOIN
comm.dbo.invmas as invmas2 ON invmas2.item_num = od2.item#
JOIN
comm.dbo.ordhrd as oh2 ON oh2.location = od2.location
AND oh2.inv_date = od2.inv_date
AND oh2.invoice# = od2.invoice#
WHERE
(oh2.type_of_rec = '01' OR oh2.type_of_rec = '02')
AND od2.inv_date >= '2017-02-01 00:00:00.000'
AND od2.inv_date <= '2017-02-28 00:00:00.000'
AND ( invmas2.category = 'uhp' OR invmas2.category = 'tour' OR invmas2.category = 'mass' OR invmas2.category = 'suv' OR invmas2.category = 'ltat' OR invmas2.category = 'ltmt' OR invmas2.category = 'lthwy' OR invmas2.category = 'snow' OR invmas2.category = 'stdls' )
GROUP BY
od2.location) as currentTires ON od.location = currentTires.location
LEFT JOIN
(SELECT
od3.location, SUM(od3.qty_shipped) as currentAlignments
FROM
comm.dbo.ordetail as od3
JOIN
comm.dbo.invmas as invmas3 ON invmas3.item_num = od3.item#
JOIN
comm.dbo.ordhrd as oh3 ON oh3.location = od3.location
AND oh3.inv_date = od3.inv_date
AND oh3.invoice# = od3.invoice#
WHERE
(oh3.type_of_rec = '01' OR oh3.type_of_rec = '02')
AND od3.inv_date >= '2017-02-01 00:00:00.000'
AND od3.inv_date <= '2017-02-28 00:00:00.000'
AND (od3.item# = '8501' OR od3.item# = '8502')
GROUP BY
od3.location) as currentAlignments ON od.location = currentAlignments.location
LEFT JOIN
(SELECT
od4.location, SUM(od4.qty_shipped) as currentLubes
FROM
comm.dbo.ordetail as od4
JOIN
comm.dbo.invmas as invmas4 ON invmas4.item_num = od4.item#
JOIN
comm.dbo.ordhrd as oh4 ON oh4.location = od4.location
AND oh4.inv_date = od4.inv_date
AND oh4.invoice# = od4.invoice#
WHERE
(oh4.type_of_rec = '01' OR oh4.type_of_rec = '02')
AND od4.inv_date >= '2017-02-01 00:00:00.000'
AND od4.inv_date <= '2017-02-28 00:00:00.000'
AND (od4.item# = '200fs' OR od4.item# = '200c' OR od4.item# = '200m' OR od4.item# = '200s')
GROUP BY
od4.location) as currentLubes ON od.location = currentLubes.location
LEFT JOIN ( SELECT od5.location,SUM(od5.qty_shipped) as currentBatteries
FROM comm.dbo.ordetail as od5
JOIN comm.dbo.invmas as invmas5
ON invmas5.item_num = od5.item#
JOIN comm.dbo.ordhrd as oh5
ON oh5.location = od5.location
AND oh5.inv_date = od5.inv_date
AND oh5.invoice# = od5.invoice#
WHERE ( oh5.type_of_rec = '01' OR oh5.type_of_rec = '02' )
AND od5.inv_date >= '2017-02-01 00:00:00.000'
AND od5.inv_date <= '2017-02-28 00:00:00.000'
AND invmas5.manufact = 'inter'
GROUP BY od5.location) as currentBatteries
ON od.location = currentBatteries.location
LEFT JOIN ( SELECT od6.location,SUM(od6.qty_shipped) as currentSiping
FROM comm.dbo.ordetail as od6
JOIN comm.dbo.invmas as invmas6
ON invmas6.item_num = od6.item#
JOIN comm.dbo.ordhrd as oh6
ON oh6.location = od6.location
AND oh6.inv_date = od6.inv_date
AND oh6.invoice# = od6.invoice#
WHERE ( oh6.type_of_rec = '01' OR oh6.type_of_rec = '02' )
AND od6.inv_date >= '2017-02-01 00:00:00.000'
AND od6.inv_date <= '2017-02-28 00:00:00.000'
AND invmas6.manufact = 'inter'
GROUP BY od6.location) as currentSiping
ON od.location = currentSiping.location
LEFT JOIN ( SELECT od7.location,COUNT(DISTINCT oh7.invoice#) as currentCarcount
FROM comm.dbo.ordetail as od7
JOIN comm.dbo.ordhrd as oh7
ON oh7.location = od7.location
AND oh7.inv_date = od7.inv_date
AND oh7.invoice# = od7.invoice#
WHERE ( oh7.type_of_rec = '01' OR oh7.type_of_rec = '02' )
AND od7.inv_date >= '2017-02-01 00:00:00.000'
AND od7.inv_date <= '2017-02-28 00:00:00.000'
AND oh7.veh_make != ''
AND od7.item# != ''
GROUP BY od7.location) as currentCarcount
ON od.location = currentCarcount.location
ORDER BY od.location
Sample data output:
There are a lot of things that could be made better here. For starters, one of the following joins below could be eliminated as the same items are returned for both od5 and od6.
LEFT JOIN ( SELECT od5.location,SUM(od5.qty_shipped) as currentBatteries
FROM comm.dbo.ordetail as od5
JOIN comm.dbo.invmas as invmas5
ON invmas5.item_num = od5.item#
JOIN comm.dbo.ordhrd as oh5
ON oh5.location = od5.location
AND oh5.inv_date = od5.inv_date
AND oh5.invoice# = od5.invoice#
WHERE ( oh5.type_of_rec = '01' OR oh5.type_of_rec = '02' )
AND od5.inv_date >= '2017-02-01 00:00:00.000'
AND od5.inv_date <= '2017-02-28 00:00:00.000'
AND invmas5.manufact = 'inter'
GROUP BY od5.location) as currentBatteries
ON od.location = currentBatteries.location
LEFT JOIN ( SELECT od6.location,SUM(od6.qty_shipped) as currentSiping
FROM comm.dbo.ordetail as od6
JOIN comm.dbo.invmas as invmas6
ON invmas6.item_num = od6.item#
JOIN comm.dbo.ordhrd as oh6
ON oh6.location = od6.location
AND oh6.inv_date = od6.inv_date
AND oh6.invoice# = od6.invoice#
WHERE ( oh6.type_of_rec = '01' OR oh6.type_of_rec = '02' )
AND od6.inv_date >= '2017-02-01 00:00:00.000'
AND od6.inv_date <= '2017-02-28 00:00:00.000'
AND invmas6.manufact = 'inter'
GROUP BY od6.location) as currentSiping
ON od.location = currentSiping.location
As for performance and readability try something like below. NOTE : I can not possibly test this, however, it may give insight to someone with more time to fiddle with performance tuning your query.
DECLARE #LowDate DATETIME = '2017-02-01 00:00:00.000'
DECLARE #HighDate DATETIME = '2017-02-28 00:00:00.000'
SELECT
DetailList.location,
currentTires = SUM(currentTires),
currentAlignments = SUM(currentAlignments),
currentLubes = SUM(currentLubes),
currentBatteries = SUM(currentBatteries),
currentSiping = SUM(currentSiping),
carCount = SUM(hasCar)
FROM
(
SELECT
od.location,
currentLubes=CASE WHEN ( od.item# = '200fs' OR od.item# = '200c' OR od.item# = '200m' OR od.item# = '200s' ) THEN od.qty_shipped ELSE NULL END,
currentAlignments=CASE WHEN ( od.item# = '8501' OR od.item# = '8502' ) THEN od.qty_shipped ELSE NULL END,
currentSiping = CASE WHEN ( invmas.item_num = 'p15' OR invmas.item_num = 'u15' ) THEN od.qty_shipped ELSE NULL END,
currentBatteries = CASE WHEN invmas.manufact = 'inter' THEN od.qty_shipped ELSE NULL END,
currentTires= CASE WHEN ( invmas.category = 'uhp' OR invmas.category = 'tour' OR invmas.category = 'mass' OR invmas.category = 'suv' OR invmas.category = 'ltat' OR
invmas.category = 'ltmt' OR invmas.category = 'lthwy' OR invmas.category = 'snow' OR invmas.category = 'stdls' ) THEN od.qty_shipped ELSE NULL END,
hasCar= CASE WHEN (oh.veh_make != '' AND od.item# !='') THEN 1 ELSE 0 END
FROM
comm.dbo.ordetail as od
LEFT JOIN comm.dbo.invmas as invmas ON invmas.item_num = od.item# --FOR currentCarcount
INNER JOIN comm.dbo.ordhrd as oh ON oh.location = od.location AND oh.inv_date = od.inv_date AND oh.invoice# = od.invoice#
WHERE
od.inv_date BETWEEN '2017-02-01 00:00:00.000' AND '2017-02-28 00:00:00.000'
AND
oh.type_of_rec IN('01','02')
)AS DetailList
GROUP BY
DetailList.location

MsSQL Query - Simplifying the code

I have the below code but it takes tooooo much time to run. Is there any way to simplify it? I need the iotransactiondate depending on the iostatus on two different columns, that's why i had to join the same tables two times.
SELECT
pg.pgrpName1 [Santiye],
p.prsncode [Sicil No],
p.[prsnname1] [Adi],
p.[prsnname2] [Soyadi],
CLT.clntName1 [Firmasi],
fg3.grp3Name1 [Gorevi],
prf.pcntrName1 [Ekibi],
lnk11.lgrp11Name1 [Kaldigi Yer],
lnk12.lgrp12Name1 +' - '+lnk12.lgrp12Name2 [Kamp/Adres],
lnk13.lgrp13Name1 [Oda No],
ttt.[iotransactiondate] [Giris Tarihi/Saati],
tt.[iotransactiondate] [Cikis Tarihi/Saati],
prsnEText4 [Vardiya],
tz.tzoneName1 [GECE/GUNDUZ]
--ps.psStartDate,
--ps.psFinishDate,
--[Giris/Cikis] = ( CASE
-- WHEN [t.iostatus] = 0 THEN 'Giris'
-- WHEN [t.iostatus] = 1 THEN 'Cikis'
-- ELSE 'Uzaya Gitti'
-- END )
FROM [Exen].[dbo].[IOTransaction] t
LEFT JOIN dbo.person p
ON t.ioPrsnRefId = p.prsnRefId
LEFT JOIN dbo.PersonShift ps
ON ps.psPrsnRefId = p.prsnRefId
LEFT JOIN dbo.TimeZoneMess tz
ON tz.tzoneRefId = ps.psTzoneRefId
LEFT JOIN dbo.[PersonGroup] pg
ON pg.pgrpRefId = p.prsnPgrpRefId
LEFT JOIN FreeGroup3 fg3
ON fg3.grp3RefId = p.prsnGrp3RefId
left join Client CLT
ON CLT.clntRefId = P.prsnClntRefId
LEFT JOIN [ProfitCenter] prf
ON prf.pcntrRefId = p.prsnPcntrRefId
LEFT JOIN LinkedGroup11 lnk11
ON lnk11.lgrp11RefId = p.prsnLgrp11RefId
LEFT JOIN LinkedGroup12 lnk12
ON lnk12.lgrp12RefId = p.prsnLgrp12RefId
LEFT JOIN LinkedGroup13 lnk13
ON lnk13.lgrp13RefId = p.prsnLgrp13RefId
LEFT JOIN [Exen].[dbo].[IOTransaction] tt
ON t.ioPrsnRefId = tt.ioPrsnRefId and tt.[iostatus] = 1
LEFT JOIN [Exen].[dbo].[IOTransaction] ttt
ON t.ioPrsnRefId = ttt.ioPrsnRefId and ttt.[iostatus] = 0
WHERE ( t.[iotransactiondate] = (SELECT Min(m.[ioTransactionDate])
FROM IOTransaction m
WHERE m.ioPrsnRefId = t.ioPrsnRefId
AND Cast(m.[iotransactiondate] AS DATE)
= Cast
(
t.[iotransactiondate] AS DATE)
GROUP BY m.ioPrsnRefId)
OR t.[iotransactiondate] = (SELECT Max(m.[iotransactiondate])
FROM IOTransaction m
WHERE m.ioPrsnRefId = t.ioPrsnRefId
AND Cast(m.[iotransactiondate] AS
DATE) =
Cast(
t.[iotransactiondate] AS DATE)
GROUP BY m.ioPrsnRefId) )
AND p.[prsnname1] IS NOT NULL
AND t.iotransactiondate > '01.12.2016 00:00:00.000'
AND ps.psStartDate <= t.[iotransactiondate]
AND ps.psFinishDate > t.[iotransactiondate]
--and p.[prsnname1] ='NAIM'
AND tz.tzoneRefId =4
GROUP BY pg.pgrpName1 ,
t.ioPrsnRefId,
prsncode,
prsnname1,
prsnname2,
t.[iotransactiondate],
tt.[iotransactiondate],
ttt.[iotransactiondate],
t.iostatus,
tz.tzoneName1,
ps.psStartDate,
ps.psFinishDate,
prsnEText4,
fg3.grp3Name1,
CLT.clntName1,
prf.pcntrName1,
lgrp11Name1,
lgrp12Name1,
lgrp12Name2,
lgrp13Name1
ORDER BY P.prsncode, t.iotransactiondate desc
Especially this part takes too much time i guess, but i couldn't find another way.
LEFT JOIN [Exen].[dbo].[IOTransaction] tt
ON t.ioPrsnRefId = tt.ioPrsnRefId and tt.[iostatus] = 1
LEFT JOIN [Exen].[dbo].[IOTransaction] ttt
ON t.ioPrsnRefId = ttt.ioPrsnRefId and ttt.[iostatus] = 0
I removed the join parts (tt. and ttt.) and select the second time with a sub-query.
SELECT
pg.pgrpName1 [Santiye],
p.prsncode [Sicil No],
p.[prsnname1] [Adi],
p.[prsnname2] [Soyadi],
CLT.clntName1 [Firmasi],
fg3.grp3Name1 [Gorevi],
prf.pcntrName1 [Ekibi],
lnk11.lgrp11Name1 [Kaldigi Yer],
lnk12.lgrp12Name1 +' - '+lnk12.lgrp12Name2 [Kamp/Adres],
lnk13.lgrp13Name1 [Oda No],
t.[iotransactiondate] [Giris Tarihi/Saati],
(SELECT
t2.[iotransactiondate]
FROM [Exen].[dbo].[IOTransaction] t2
WHERE ( t2.[iotransactiondate] = (SELECT Min(m.[ioTransactionDate])
FROM IOTransaction m
WHERE m.ioPrsnRefId = t2.ioPrsnRefId
AND Cast(m.[iotransactiondate] AS DATE)
= Cast
(
t2.[iotransactiondate] AS DATE)
GROUP BY m.ioPrsnRefId)
OR t2.[iotransactiondate] = (SELECT Max(m.[iotransactiondate])
FROM IOTransaction m
WHERE m.ioPrsnRefId = t2.ioPrsnRefId
AND Cast(m.[iotransactiondate] AS
DATE) =
Cast(
t2.[iotransactiondate] AS DATE)
GROUP BY m.ioPrsnRefId) )
AND p.[prsnname1] IS NOT NULL
AND t2.iotransactiondate > '01.12.2016 00:00:00.000'
AND ps.psStartDate <= t2.[iotransactiondate]
AND ps.psFinishDate > t2.[iotransactiondate]
--and p.[prsnname1] ='NAIM'
--AND tz.tzoneRefId =4
and ioStatus = 1
and cast(t2.ioTransactionDate as date) = cast(t.ioTransactionDate as date) and t.ioPrsnRefId = t2.ioPrsnRefId
GROUP BY
t2.[iotransactiondate]
)
AS [Cikis Tarihi/Saati],
prsnEText4 [Vardiya],
tz.tzoneName1 [GECE/GUNDUZ]
--ps.psStartDate,
--ps.psFinishDate,
--[Giris/Cikis] = ( CASE
-- WHEN [t.iostatus] = 0 THEN 'Giris'
-- WHEN [t.iostatus] = 1 THEN 'Cikis'
-- ELSE 'Uzaya Gitti'
-- END )
FROM [Exen].[dbo].[IOTransaction] t
LEFT JOIN dbo.person p
ON t.ioPrsnRefId = p.prsnRefId
LEFT JOIN dbo.PersonShift ps
ON ps.psPrsnRefId = p.prsnRefId
LEFT JOIN dbo.TimeZoneMess tz
ON tz.tzoneRefId = ps.psTzoneRefId
LEFT JOIN dbo.[PersonGroup] pg
ON pg.pgrpRefId = p.prsnPgrpRefId
LEFT JOIN FreeGroup3 fg3
ON fg3.grp3RefId = p.prsnGrp3RefId
left join Client CLT
ON CLT.clntRefId = P.prsnClntRefId
LEFT JOIN [ProfitCenter] prf
ON prf.pcntrRefId = p.prsnPcntrRefId
LEFT JOIN LinkedGroup11 lnk11
ON lnk11.lgrp11RefId = p.prsnLgrp11RefId
LEFT JOIN LinkedGroup12 lnk12
ON lnk12.lgrp12RefId = p.prsnLgrp12RefId
LEFT JOIN LinkedGroup13 lnk13
ON lnk13.lgrp13RefId = p.prsnLgrp13RefId
WHERE ( t.[iotransactiondate] = (SELECT Min(m.[ioTransactionDate])
FROM IOTransaction m
WHERE m.ioPrsnRefId = t.ioPrsnRefId
AND Cast(m.[iotransactiondate] AS DATE)
= Cast
(
t.[iotransactiondate] AS DATE)
GROUP BY m.ioPrsnRefId)
OR t.[iotransactiondate] = (SELECT Max(m.[iotransactiondate])
FROM IOTransaction m
WHERE m.ioPrsnRefId = t.ioPrsnRefId
AND Cast(m.[iotransactiondate] AS
DATE) =
Cast(
t.[iotransactiondate] AS DATE)
GROUP BY m.ioPrsnRefId) )
AND p.[prsnname1] IS NOT NULL
AND t.iotransactiondate > '01.12.2016 00:00:00.000'
AND ps.psStartDate <= t.[iotransactiondate]
AND ps.psFinishDate > t.[iotransactiondate]
--and p.[prsnname1] ='NAIM'
AND tz.tzoneRefId =4
and ioStatus = 0
GROUP BY pg.pgrpName1 ,
t.ioPrsnRefId,
prsncode,
prsnname1,
prsnname2,
t.[iotransactiondate],
t.iostatus,
tz.tzoneName1,
ps.psStartDate,
ps.psFinishDate,
prsnEText4,
fg3.grp3Name1,
CLT.clntName1,
prf.pcntrName1,
lgrp11Name1,
lgrp12Name1,
lgrp12Name2,
lgrp13Name1

an expression of non-boolean type specified in a context where a condition is expected near 'type'

I am new to SSRS topics and I got this error while preparing the report plz help me to solve this. I have kept the query here kindly go through it.
SELECT T0.DocNum AS 'SO#', T6.DocNum as 'PO#', t1.LineTotal AS 'SO Amount', T6.DocEntry, T0.CardName, T6.U_enduserName, T11.QryGroup10 AS 'Major A/C Y/N',
T6.DocEntry AS Expr1, T6.CardCode, T6.CardName AS Expr2, T6.NumAtCard, T6.DocDate, t5.ItemCode, t5.Dscription, T7.U_itmdes, t5.Quantity, t5.LineTotal,
CASE WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal] * 2.5 ELSE T5.[LineTotal] END AS 'LineTotal with DTS amt', T10.ItmsGrpNam, T8.Location,
CASE WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal' ELSE 'Product' END AS 'Lic Type'
If((((T10.ItmsGrpNam="ADESK-AEC" and T10.ItmsGrpNam="ADESK-AEC-INFRA") and T1.Lic Type="Product" and T11.QryGroup10="No")),"AEC - ENI",If(((T10.ItmsGrpNam="ADESK-OPEN" and T10.ItmsGrpNam="ADESK-HORIZONTAL") and T1.Lic Type="Product" and T11.QryGroup10="No"),"PSEB",If(((T10.ItmsGrpNam="ADESK-M&E" or T10.ItmsGrpNam="ADESK-MFG") and T1.Lic Type="Product" and T11.QryGroup10="No"),T10.ItmsGrpNam,If(((T10.ItmsGrpNam="ADESK-AEC" and T10.ItmsGrpNam="ADESK-AEC-INFRA") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"AEC & ENI - Sub Renewal",If(((T10.ItmsGrpNam="ADESK-OPEN" and T10.ItmsGrpNam="ADESK-HORIZONTAL") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"PSEB - Sub Renewal",If(((T10.ItmsGrpNam="ADESK-M&E" or T10.ItmsGrpNam="ADESK-MFG") and T1.Lic Type="Renewal" and T11.QryGroup10="No"),"MFG - Sub Renewal","MFG - Sub Renewal"))))))
FROM OCRD AS T11 INNER JOIN
ORDR AS T0 ON T11.CardCode = T0.CardCode INNER JOIN
RDR1 AS t1 ON T0.DocEntry = t1.DocEntry LEFT OUTER JOIN
POR1 AS t3 ON t3.BaseEntry = t1.DocEntry AND t3.BaseLine = t1.LineNum AND t3.ItemCode = t1.ItemCode LEFT OUTER JOIN
PDN1 AS t4 ON t4.BaseEntry = t3.DocEntry AND t4.BaseLine = t3.LineNum AND t4.ItemCode = t3.ItemCode INNER JOIN
PCH1 AS t5 ON t5.BaseEntry = t4.DocEntry AND t5.ItemCode = t4.ItemCode AND t5.BaseLine = t4.LineNum AND t5.TargetType <> 19 INNER JOIN
OPCH AS T6 ON t5.DocEntry = T6.DocEntry INNER JOIN
OITM AS T7 ON t5.ItemCode = T7.ItemCode INNER JOIN
OLCT AS T8 ON t5.LocCode = T8.Code CROSS JOIN
OITG AS T10
WHERE (T10.ItmsTypCod = (CASE WHEN T7.[QryGroup1] = 'y' THEN 1 WHEN T7.[QryGroup2] = 'y' THEN 2 WHEN T7.[QryGroup3] = 'y' THEN 3 WHEN T7.[QryGroup4] = 'y' THEN
4 WHEN T7.[QryGroup5] = 'y' THEN 5 WHEN T7.[QryGroup6] = 'y' THEN 6 WHEN T7.[QryGroup7] = 'y' THEN 7 WHEN T7.[QryGroup8] = 'y' THEN 8 WHEN T7.[QryGroup9]
= 'y' THEN 9 WHEN T7.[QryGroup60] = 'y' THEN 60 ELSE 0 END)) AND (T6.CardCode <> 'VDD1-100233')
and T6.[DocDate] >=(#date1) and T6.[DocDate] <=(#date2)
Try to do something like this first,
DECLARE #date1 AS DATETIME = '' --your date1
DECLARE #date2 AS DATETIME = '' --your date2
SELECT *
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode=T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry=t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry =t1.DocEntry AND t3.BaseLine=t1.LineNum
AND t3.ItemCode=t1.ItemCode LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry=t3.DocEntry
AND t4.BaseLine=t3.LineNum
AND t4.ItemCode=t3.ItemCode INNER JOIN PCH1 AS t5 ON t5.BaseEntry=t4.DocEntry
AND t5.ItemCode=t4.ItemCode
AND t5.BaseLine=t4.LineNum
AND t5.TargetType<>19 INNER JOIN OPCH AS T6 ON t5.DocEntry=T6.DocEntry INNER
JOIN OITM AS T7 ON t5.ItemCode=T7.ItemCode INNER JOIN OLCT AS T8 ON t5.LocCode
=T8.Code CROSS JOIN OITG AS T10 WHERE (
T10.ItmsTypCod=(
CASE
WHEN T7.[QryGroup1]='y' THEN 1
WHEN T7.[QryGroup2]='y' THEN 2
WHEN T7.[QryGroup3]='y' THEN 3
WHEN T7.[QryGroup4]='y' THEN 4
WHEN T7.[QryGroup5]='y' THEN 5
WHEN T7.[QryGroup6]='y' THEN 6
WHEN T7.[QryGroup7]='y' THEN 7
WHEN T7.[QryGroup8]='y' THEN 8
WHEN T7.[QryGroup9]='y' THEN 9
WHEN T7.[QryGroup60]='y' THEN 60
ELSE 0
END
)
)
AND (T6.[CardCode] <> 'VDD1-100233')
AND T6.[DocDate] >= (#date1)
AND T6.[DocDate] <= (#date2)
If it gives you result then try to add below variables one by one,
T0.DocNum AS 'SO#'
,T6.DocNum AS 'PO#'
,t1.LineTotal AS 'SO Amount'
,T6.DocEntry
,T0.CardName
,T6.U_enduserName
,T11.QryGroup10 AS 'Major A/C Y/N'
,T6.DocEntry AS Expr1
,T6.CardCode
,T6.CardName AS Expr2
,T6.NumAtCard
,T6.DocDate
,t5.ItemCode
,t5.Dscription
,T7.U_itmdes
,t5.Quantity
,t5.LineTotal
,CASE
WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal]*2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt'
,T10.ItmsGrpNam
,T8.Location
,CASE
WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type'
IF (
(
(
(
T10.ItmsGrpNam="ADESK-AEC"
AND T10.ItmsGrpNam="ADESK-AEC-INFRA"
)
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
)
,[AEC - ENI]
,IF(
(
(
T10.ItmsGrpNam="ADESK-OPEN"
AND T10.ItmsGrpNam="ADESK-HORIZONTAL"
)
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
,"PSEB"
,IF(
(
(T10.ItmsGrpNam="ADESK-M&E" OR T10.ItmsGrpNam="ADESK-MFG")
AND T1.[Lic TYPE]="Product"
AND T11.QryGroup10="No"
)
,T10.ItmsGrpNam
,IF(
(
(
T10.ItmsGrpNam="ADESK-AEC"
AND T10.ItmsGrpNam="ADESK-AEC-INFRA"
)
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"AEC & ENI - Sub Renewal"
,IF(
(
(
T10.ItmsGrpNam="ADESK-OPEN"
AND T10.ItmsGrpNam="ADESK-HORIZONTAL"
)
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"PSEB - Sub Renewal"
,IF(
(
(T10.ItmsGrpNam="ADESK-M&E" OR T10.ItmsGrpNam="ADESK-MFG")
AND T1.[Lic TYPE]="Renewal"
AND T11.QryGroup10="No"
)
,"MFG - Sub Renewal"
,"MFG - Sub Renewal"
)
)
)
)
)
)
Note: It will throw error:
Incorrect syntax near ','.
Make it as per your requirement. If is alias then make sure it should work as single variable.
Also I noted you are fetching different variables but you have not put , after AS 'Lic Type'. Check this also.
Below query using CASE ,
DECLARE #date1 AS DATETIME
DECLARE #date2 AS DATETIME
SELECT T0.DocNum AS 'SO#'
,T6.DocNum AS 'PO#'
,t1.LineTotal AS 'SO Amount'
,T6.DocEntry
,T0.CardName
,T6.U_enduserName
,T11.QryGroup10 AS 'Major A/C Y/N'
,T6.DocEntry AS Expr1
,T6.CardCode
,T6.CardName AS Expr2
,T6.NumAtCard
,T6.DocDate
,t5.ItemCode
,t5.Dscription
,T7.U_itmdes
,t5.Quantity
,t5.LineTotal
,CASE
WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal]*2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt'
,T10.ItmsGrpNam
,T8.Location
,CASE
WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type'
,
CASE
WHEN T10.ItmsGrpNam='ADESK-AEC' AND T10.ItmsGrpNam='ADESK-AEC-INFRA' AND T1.[Lic TYPE]='Product' AND T11.QryGroup10='No"' THEN 'AEC - ENI'
WHEN T10.ItmsGrpNam='ADESK-OPEN' AND T10.ItmsGrpNam='ADESK-HORIZONTAL' AND
T1.[Lic TYPE]='Product' AND T11.QryGroup10='No' THEN 'PSEB'
WHEN (T10.ItmsGrpNam='ADESK-M&E' OR T10.ItmsGrpNam='ADESK-MFG') AND T1.[Lic
TYPE]='Product' AND T11.QryGroup10='No' THEN T10.ItmsGrpNam
WHEN T10.ItmsGrpNam='ADESK-AEC' AND T10.ItmsGrpNam='ADESK-AEC-INFRA' AND T1.[Lic
TYPE]='Renewal' AND T11.QryGroup10='No' THEN '"AEC & ENI - Sub Renewal'
WHEN T10.ItmsGrpNam='ADESK-OPE' AND T10.ItmsGrpNam='ADESK-HORIZONTAL' AND
T1.[Lic TYPE]='Renewal' AND T11.QryGroup10='No' THEN
'PSEB - Sub Renewal'
WHEN (T10.ItmsGrpNam='ADESK-M&E' OR T10.ItmsGrpNam='ADESK-MFG') AND [T1.Lic
TYPE]='Renewal' AND T11.QryGroup10='No' THEN 'MFG - Sub Renewal'
ELSE 'MFG - Sub Renewal'
END
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode=T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry=t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry =t1.DocEntry AND t3.BaseLine=t1.LineNum
AND t3.ItemCode=t1.ItemCode LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry=t3.DocEntry
AND t4.BaseLine=t3.LineNum
AND t4.ItemCode=t3.ItemCode INNER JOIN PCH1 AS t5 ON t5.BaseEntry=t4.DocEntry
AND t5.ItemCode=t4.ItemCode
AND t5.BaseLine=t4.LineNum
AND t5.TargetType<>19 INNER JOIN OPCH AS T6 ON t5.DocEntry=T6.DocEntry INNER
JOIN OITM AS T7 ON t5.ItemCode=T7.ItemCode INNER JOIN OLCT AS T8 ON t5.LocCode
=T8.Code CROSS JOIN OITG AS T10 WHERE (
T10.ItmsTypCod=(
CASE
WHEN T7.[QryGroup1]='y' THEN 1
WHEN T7.[QryGroup2]='y' THEN 2
WHEN T7.[QryGroup3]='y' THEN 3
WHEN T7.[QryGroup4]='y' THEN 4
WHEN T7.[QryGroup5]='y' THEN 5
WHEN T7.[QryGroup6]='y' THEN 6
WHEN T7.[QryGroup7]='y' THEN 7
WHEN T7.[QryGroup8]='y' THEN 8
WHEN T7.[QryGroup9]='y' THEN 9
WHEN T7.[QryGroup60]='y' THEN 60
ELSE 0
END
)
)
AND (T6.[CardCode] <> 'VDD1-100233')
AND T6.[DocDate] >= (#date1)
AND T6.[DocDate] <= (#date2)
You have the following in several places in select part:
T1.Lic Type="Product"
You have to delimit that column. Change to this:
T1.[Lic Type]="Product"
It is a pain to gebug so many IIF operators. Change to CASE expressions. You will gain both in readability and standardization of your code. Also change double quotes to single quotes.
case when T10.ItmsGrpNam='ADESK-AEC' and T10.ItmsGrpNam='ADESK-AEC-INFRA' and T1.[Lic Type]='Product' and T11.QryGroup10='No"' then 'AEC - ENI'
when T10.ItmsGrpNam='ADESK-OPEN' and T10.ItmsGrpNam='ADESK-HORIZONTAL' and T1.[Lic Type]='Product' and T11.QryGroup10='No' then 'PSEB'
when (T10.ItmsGrpNam='ADESK-M&E' or T10.ItmsGrpNam='ADESK-MFG') and T1.[Lic Type]='Product' and T11.QryGroup10='No' then T10.ItmsGrpNam
when T10.ItmsGrpNam='ADESK-AEC' and T10.ItmsGrpNam='ADESK-AEC-INFRA' and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then'"AEC & ENI - Sub Renewal'
when T10.ItmsGrpNam='ADESK-OPE' and T10.ItmsGrpNam='ADESK-HORIZONTAL' and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then 'PSEB - Sub Renewal'
when (T10.ItmsGrpNam='ADESK-M&E' or T10.ItmsGrpNam='ADESK-MFG') and T1.[Lic Type]='Renewal' and T11.QryGroup10='No' then 'MFG - Sub Renewal'
else 'MFG - Sub Renewal' end
EDIT:
Here is the full statement:
DECLARE #date1 DATETIME, #date2 DATETIME
SELECT T0.DocNum AS 'SO#' ,
T6.DocNum AS 'PO#' ,
t1.LineTotal AS 'SO Amount' ,
T6.DocEntry ,
T0.CardName ,
T6.U_enduserName ,
T11.QryGroup10 AS 'Major A/C Y/N' ,
T6.DocEntry AS Expr1 ,
T6.CardCode ,
T6.CardName AS Expr2 ,
T6.NumAtCard ,
T6.DocDate ,
t5.ItemCode ,
t5.Dscription ,
T7.U_itmdes ,
t5.Quantity ,
t5.LineTotal ,
CASE WHEN T7.[U_itmdes] LIKE '%Desktop%%' THEN T5.[LineTotal] * 2.5
ELSE T5.[LineTotal]
END AS 'LineTotal with DTS amt' ,
T10.ItmsGrpNam ,
T8.Location ,
CASE WHEN T1.[Dscription] LIKE '%Renewal%%' THEN 'Renewal'
ELSE 'Product'
END AS 'Lic Type' ,
CASE WHEN T10.ItmsGrpNam = 'ADESK-AEC'
AND T10.ItmsGrpNam = 'ADESK-AEC-INFRA'
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No"' THEN 'AEC - ENI'
WHEN T10.ItmsGrpNam = 'ADESK-OPEN'
AND T10.ItmsGrpNam = 'ADESK-HORIZONTAL'
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No' THEN 'PSEB'
WHEN ( T10.ItmsGrpNam = 'ADESK-M&E'
OR T10.ItmsGrpNam = 'ADESK-MFG'
)
AND T1.[Lic Type] = 'Product'
AND T11.QryGroup10 = 'No' THEN T10.ItmsGrpNam
WHEN T10.ItmsGrpNam = 'ADESK-AEC'
AND T10.ItmsGrpNam = 'ADESK-AEC-INFRA'
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN '"AEC & ENI - Sub Renewal'
WHEN T10.ItmsGrpNam = 'ADESK-OPE'
AND T10.ItmsGrpNam = 'ADESK-HORIZONTAL'
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN 'PSEB - Sub Renewal'
WHEN ( T10.ItmsGrpNam = 'ADESK-M&E'
OR T10.ItmsGrpNam = 'ADESK-MFG'
)
AND T1.[Lic Type] = 'Renewal'
AND T11.QryGroup10 = 'No' THEN 'MFG - Sub Renewal'
ELSE 'MFG - Sub Renewal'
END
FROM OCRD AS T11
INNER JOIN ORDR AS T0 ON T11.CardCode = T0.CardCode
INNER JOIN RDR1 AS t1 ON T0.DocEntry = t1.DocEntry
LEFT OUTER JOIN POR1 AS t3 ON t3.BaseEntry = t1.DocEntry
AND t3.BaseLine = t1.LineNum
AND t3.ItemCode = t1.ItemCode
LEFT OUTER JOIN PDN1 AS t4 ON t4.BaseEntry = t3.DocEntry
AND t4.BaseLine = t3.LineNum
AND t4.ItemCode = t3.ItemCode
INNER JOIN PCH1 AS t5 ON t5.BaseEntry = t4.DocEntry
AND t5.ItemCode = t4.ItemCode
AND t5.BaseLine = t4.LineNum
AND t5.TargetType <> 19
INNER JOIN OPCH AS T6 ON t5.DocEntry = T6.DocEntry
INNER JOIN OITM AS T7 ON t5.ItemCode = T7.ItemCode
INNER JOIN OLCT AS T8 ON t5.LocCode = T8.Code
CROSS JOIN OITG AS T10
WHERE ( T10.ItmsTypCod = ( CASE WHEN T7.[QryGroup1] = 'y' THEN 1
WHEN T7.[QryGroup2] = 'y' THEN 2
WHEN T7.[QryGroup3] = 'y' THEN 3
WHEN T7.[QryGroup4] = 'y' THEN 4
WHEN T7.[QryGroup5] = 'y' THEN 5
WHEN T7.[QryGroup6] = 'y' THEN 6
WHEN T7.[QryGroup7] = 'y' THEN 7
WHEN T7.[QryGroup8] = 'y' THEN 8
WHEN T7.[QryGroup9] = 'y' THEN 9
WHEN T7.[QryGroup60] = 'y' THEN 60
ELSE 0
END ) )
AND ( T6.CardCode <> 'VDD1-100233' )
AND T6.[DocDate] >= ( #date1 )
AND T6.[DocDate] <= ( #date2 )

Resources