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
Related
I am running the below query which is failing when it fills up the tempdb (170GB). It fails after around 1 hour.
the script below :
--Select Query BOM collection retail report
Declare #Company Nvarchar(50) ='HMFI'
Declare #Product Nvarchar(50) =Null
select Upper (Be.DataAreaId)Company ,BE.BOM,BE.Product
,Max(ProItemName)ProItemName
,Max(ProUnitID)ProUnitID
,Be.Material,Max(MaterialItemName)MaterialItemName
,Be.UNITID MaterialUnitID
,Sum (Be.BOMQTY)MaterialQty
,Max (MaterialService) MaterialType
from ExpBom_HMFI BE
Outer Apply (SELECT UNITID ProUnitID FROM INVENTTABLEMODULE A With (Nolock) WHERE DATAAREAID = #Company AND A.ITEMID =BE.Product AND MODULETYPE = 0)ProUnitID
Outer Apply(SELECT ITEMNAME ProItemName FROM INVENTTABLE B With (Nolock) WHERE DATAAREAID = #Company AND B.ITEMID = BE.Product)ProItemName
Outer Apply(SELECT ITEMNAME MaterialItemName FROM INVENTTABLE C With (Nolock) WHERE DATAAREAID = #Company AND C.ITEMID = Be.Material)MaterialItemName
Outer Apply(SELECT Case When ITEMTYPE=0 Then 'Item' When ITEMTYPE=1 Then 'BOM' When ITEMTYPE=2 Then 'Service Item' End MaterialService
FROM INVENTTABLE With (Nolock) WHERE DATAAREAID = #Company AND ITEMID = Be.Material)MaterialService
Where BE.DataAreaId in (#Company) and (#Product Is null Or Be.Product In(Select StringValue From Split(#Product,',')))
Group by Be.DataAreaId,BE.BOM,BE.Product,Be.Material ,Be.UNITID
Order By Be.DataAreaId,BE.BOM,BE.Product,Be.Material
option (maxrecursion 0)
--now Viewing the data collected
with ExpBom (
DataAreaId,
Bom,
Product,
Material,
BomDepth,
BOMQTY,
Unitid,
BomPath
) as (
select
bv.DataAreaId,
bv.BomId,
bv.ItemId,
b.ItemId,
1,
Convert (NUMERIC(18,8), b.BOMQTY) BOMQTY,
Convert (Nvarchar(10),b.UNITID )Unitid,
convert(Nvarchar(max), bv.ItemId + '|' + b.ItemId) as BomPath
from BomVersion bv With (Nolock)
join InventTable ibv With (Nolock)
on ibv.DataAreaId = bv.DataAreaId
and ibv.ItemId = bv.ItemId
join Bom b With (Nolock)
on b.DataAreaId = bv.DataAreaId
and b.BomId = bv.BomId
join InventTable ib With (Nolock)
on ib.DataAreaId = b.DataAreaId
and ib.ItemId = b.ItemId
where bv.Approved = 1
and bv.Active = 1
and bv.FromDate < getdate()
and (bv.ToDate = '01-01-1900' or bv.ToDate >= getdate())
and b.FromDate < getdate()
and (b.ToDate = '01-01-1900' or b.ToDate >= getdate())
and b.DATAAREAID in ('HMFI')
union all
select
bv.DataAreaId,
bv.BomId,
bv.ItemId,
eb.Material,
eb.BomDepth + 1,
Convert (NUMERIC(18,8),B.BOMQTY * eb.BOMQTY)BOMQTY,
Convert (Nvarchar(10),eb.UNITID )Unitid,
convert(Nvarchar(max), bv.ItemId + '|' + eb.BomPath) as BomPath
from BomVersion bv With (Nolock)
join InventTable ibv With (Nolock)
on ibv.DataAreaId = bv.DataAreaId
and ibv.ItemId = bv.ItemId
join Bom b With (Nolock)
on b.DataAreaId = bv.DataAreaId
and b.BomId = bv.BomId
join ExpBom eb
on eb.DataAreaId = b.DataAreaId
and eb.Product = b.ItemId
where bv.Approved = 1
and bv.Active = 1
and bv.FromDate < getdate()
and (bv.ToDate = '01-01-1900' or bv.ToDate >= getdate())
and b.FromDate < getdate()
and (b.ToDate = '01-01-1900' or b.ToDate >= getdate())
and b.DATAAREAID in ('HMFI')
)
select * from ExpBOM
Where Material Not in (Select BOMV.ITEMID From BomVersion BOMV With (Nolock) Where BOMV.DataAreaId In( 'HMFI' ) and BOMV.Approved = 1
and BOMV.Active = 1
and BOMV.FromDate < getdate()
and (BOMV.ToDate = '01-01-1900' or BOMV.ToDate >= getdate()) )
I'm not sure if the JOINS are causing the issue
Estimated execution plan is below:
Data collection :
https://www.brentozar.com/pastetheplan/?id=S1UsXn4Po
Data view:
https://www.brentozar.com/pastetheplan/?id=BJDUBn4wi
Please advise
this report was working fine on daily basis without filling tempdb usualy it was taking 1 min to execute suddenly it stoped for unknown reason although there's no changes done on server/database levels
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
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);
WITH TEMP_CTE (ID,currentposition,equiptmentno,isocode,carrier,ishazardous,isreefer,CallID)
AS
(
SELECT a.ID,
a.newposition AS currentposition,
qce.equiptmentno,
qce.isocode,
qce.carrier,
qcee.ishazardous,
qcee.isreefer,qce.CallID
FROM (SELECT Row_number()
OVER (
partition BY callequipmentid
ORDER BY e.movedate DESC) RN,
e.*
FROM qbtcallequipmentexecution e
WHERE e.isactive = 1)a
INNER JOIN qbtcallequipment AS qce
ON a.callequipmentid = qce.id
AND qce.callid = #CallID
AND a.rn = 1
AND operationtype = 'LOAD'
INNER JOIN qbtcallediequipment AS qcee
ON qcee.equiptmentno = qce.equiptmentno
INNER JOIN qbtcalledi qcd
ON qcee.callediid = qcd.id
AND qcd.callid = #CallID
INNER JOIN commlov cl
ON cl.id = qcd.editypeid
AND cl.code = 'MOVINS'
AND siteid = #SiteID
UNION ALL
SELECT ddqce.ID,
ddqce.currentposition AS currentposition,
dqcee.equiptmentno,
dqcee.isocode,
dqcee.carrier,
dqcee.ishazardous,
dqcee.isreefer,ddqce.CallID
FROM qbtcallediequipment AS dqcee
INNER JOIN qbtcalledi dqcd
ON dqcee.callediid = dqcd.id
AND dqcd.callid = #CallID
INNER JOIN commlov dcl
ON dcl.id = dqcd.editypeid
AND dcl.code = 'RDBAPL'
AND siteid = #SiteID
INNER JOIN qbtcallequipment ddqce
ON ddqce.equiptmentno = dqcee.equiptmentno
AND ddqce.callid = #CallID
AND ddqce.isactive = 1
WHERE dqcee.equiptmentno NOT IN (SELECT dqce.equiptmentno
FROM (SELECT Row_number()
OVER (
partition BY
callequipmentid
ORDER BY e.movedate DESC)
RN,
e.*
FROM qbtcallequipmentexecution e
WHERE e.isactive = 1)a
INNER JOIN qbtcallequipment dqce
ON a.callequipmentid = dqce.id
AND dqce.callid = #CallID
AND a.rn = 1
AND movetypeid = (SELECT id
FROM
commlov
WHERE
code =
'DSCR'
AND
siteid =
#SiteID))
),
FIRST_CTE
AS
(
select ID,currentposition,equiptmentno,isocode,carrier,ishazardous,isreefer,CallID, ROW_NUMBER() over (PARTITION by currentposition order by equiptmentno desc ) as RN from TEMP_CTE
),
SECOND_CTE
AS
(
select TC.ID,currentposition,equiptmentno,isocode,carrier,ishazardous,isreefer,CallID,'Flying' as Anomaly
from TEMP_CTE as TC
inner join schmtVesselSchedule svs on svs.ID=TC.CallID
inner join qbtVesselProfile AS QVP ON svs.VesselID=QVP.VesselID
WHERE (cast(RIGHT(TC.currentposition,2) as int)>2 AND cast(RIGHT(TC.currentposition,2) as int)<cast(QVP.MaxTierUnderDeck as int)) OR (cast (RIGHT(TC.currentposition,2) as int)>cast (QVP.StartNoOverDeck as int) AND cast (RIGHT(TC.currentposition,2) as int) < cast (QVP.EndNoOverDeck as int)) AND (LEFT(TC.currentposition, LEN(cast(TC.currentposition as int)-2)+(case when LEN(cast(RIGHT(TC.currentposition,2) as int)-2)=1 then '0'+CONVERT(varchar(10), (RIGHT(TC.currentposition,2)-2)) else CONVERT(varchar(10), (RIGHT(TC.currentposition,2)-2)) end )) is null)
)
select
ID,
currentposition,
equiptmentno,
isocode,
carrier,
ishazardous,
isreefer,CallID,(case when RIGHT(currentposition,2)='99' then 'Dummy' else 'Same Slot' end) as Anomaly
from FIRST_CTE where RN > 1 OR RIGHT(currentposition,2) = '99'
union all
select
ID,
currentposition,
equiptmentno,
isocode,
carrier,
ishazardous,
isreefer,CallID,Anomaly
from SECOND_CTE
Error comes in where condition of SECOND_CTE. In that i used temp_cte for data purpose and manupulate it over there. Giving Error "
Conversion failed when converting the nvarchar value 'RT' to data type
int
. I have changed data type nvarchar to varchar of that column it also not working.And there is not char value in that column. It works fine in ssms but not working from Visual Studio"
i have the below code which is working fine.
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],
cast(t.ioTransactionDate as date) as Tarih,
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 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]
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 >= '00:00:00 11.12.2016'
AND t.iotransactiondate <= '23:59:00 15.12.2016'
AND ps.psStartDate <= t.[iotransactiondate]
AND ps.psFinishDate > t.[iotransactiondate]
AND tz.tzoneRefId =5
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
but i need the next day data for [Cikis Tarihi/Saati] column , that's why i revised that part as
and cast(t2.ioTransactionDate as date) = cast(dateadd(day,1,t.ioTransactionDate) as date)
for example, when the column [Giris Tarihi/Saati] is 2016-12-12 , the data on the column [Cikis Tarihi/Saati] should be 2016-12-13
but it returns an error
Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1
value. This is not permitted when the subquery follows =, !=, <, <= ,
, >= or when the subquery is used as an expression.
what am i doing wrong ?
any suggestions ?