Im looking the most efficient way to resolve this.
I have to create a Query SQL using AdventureWorks database. This Query SQL must return the fields As shown below
declare #fecha datetime
set #fecha = GETDATE()-1365
declare #MPid int
set #MPid = 50
select OH.CustomerID, OH.SalesPersonID,
'Month' = Month(OH.OrderDate),
PP.Name,
pp.MakeFlag,
'CantProduct' = SUM(SOD.OrderQty),
'MinUnitPrice' = 0 ,
'MaxUnitPrice' = 0
from sales.SalesOrderHeader OH JOIN sales.SalesOrderDetail SOD ON OH.SalesOrderID = SOD.SalesOrderID
JOIN Production.Product PP ON SOD.ProductID = PP.ProductID
where OH.OrderDate > DATEADD(year,-1,#fecha) and pp.ProductID > #MPid
group by OH.CustomerID, OH.SalesPersonID, Month(OH.OrderDate), PP.Name, pp.MakeFlag
An example of the results
Instead of MinUnitPrice and MaxUnitPrice equal to 0, should obtain the maximum and minimum prices.
Can it be resolved without using temporary tables? Or which would be the most efficient solution?
Thanks
The solution
declare #fecha datetime
declare #MPid int
set #fecha = GETDATE()-1365
set #MPid = 50
select ROW_NUMBER() OVER(ORDER BY OH.CustomerID ASC) AS ID, OH.CustomerID, OH.SalesPersonID, 'Month' = Month(OH.OrderDate),PP.Name, pp.MakeFlag, 'CantProduct' = SUM(SOD.OrderQty),
'MinUnitPrice' = min(SOD3.MinUnitPrice) , 'MaxUnitPrice' = max(SOD5.MaxUnitPrice)
from sales.SalesOrderHeader OH Join sales.SalesOrderDetail SOD ON OH.SalesOrderID = SOD.SalesOrderID
Join Production.Product PP ON SOD.ProductID = PP.ProductID
Join ( select SOD2.ProductID, SOD2.SalesOrderID, 'MinUnitPrice' = Min(SOD2.UnitPrice) from sales.SalesOrderDetail SOD2
group by SOD2.ProductID ,SOD2.SalesOrderID ) SOD3 ON SOD3.ProductID = SOD.ProductID and SOD3.SalesOrderID = SOD.SalesOrderID
Join ( select SOD4.ProductID, SOD4.SalesOrderID, 'MaxUnitPrice' = Max(SOD4.UnitPrice) from sales.SalesOrderDetail SOD4
group by SOD4.ProductID ,SOD4.SalesOrderID ) SOD5 ON SOD5.ProductID = SOD.ProductID and SOD5.SalesOrderID = SOD.SalesOrderID
where OH.OrderDate > DATEADD(year,-1,#fecha) and pp.ProductID > #MPid
group by OH.CustomerID, OH.SalesPersonID, Month(OH.OrderDate), PP.Name, pp.MakeFlag
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
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 sql request which take to much time to execute, any suggestions to make it faster?
DECLARE #Today DATETIME;
DECLARE #TwoWeeksAgo
DATETIME; SET #Today = GETDATE();
SET #TwoWeeksAgo = DATEADD(DAY, -14, GETDATE());
SELECT TOP ${selectSalesByMall} s.title, s.imageUrl, count(sv.saleid) as mostViewPeriod14Days, s.guid, br.title as brand, s.id as saleId, stm.mallId
FROM dbo.Sales s
INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON s.id = b_key.saleId
INNER JOIN dbo.Brands br ON s.BrandId = br.Id
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId
INNER JOIN dbo.SalesToMall stm ON s.id = stm.saleId
LEFT JOIN dbo.SaleView sv2 on sv2.id = sv.id and sv2.userId = ${user['userID']}
WHERE sv.Date
BETWEEN #TwoWeeksAgo
AND #Today
AND sv2.id IS NULL
AND s.isActive = 1
AND stm.mallId = ${user['mallId']}
AND br.id != ${user['favBrand']['brandId']}
AND s.id NOT IN (SELECT uess.saleID FROM dbo.UsersEmailsSalesSent uess WHERE uess.userID = ${user['userID']})
GROUP BY s.title, s.imageUrl, s.guid, br.title, s.id, stm.mallId
ORDER BY mostViewPeriod14Days DESC
one improvement could be changing the "not in" to "not exists":
DECLARE #Today DATETIME;
DECLARE #TwoWeeksAgo
DATETIME; SET #Today = GETDATE();
SET #TwoWeeksAgo = DATEADD(DAY, -14, GETDATE());
SELECT TOP ${selectSalesByMall} s.title, s.imageUrl, count(sv.saleid) as mostViewPeriod14Days, s.guid, br.title as brand, s.id as saleId, stm.mallId
FROM dbo.Sales s
INNER JOIN dbo.KEY_BrandcategoryToSale b_key ON s.id = b_key.saleId
INNER JOIN dbo.Brands br ON s.BrandId = br.Id
INNER JOIN dbo.SaleView sv ON s.id = sv.saleId
INNER JOIN dbo.SalesToMall stm ON s.id = stm.saleId
LEFT JOIN dbo.SaleView sv2 on sv2.id = sv.id and sv2.userId = ${user['userID']}
WHERE sv.Date
BETWEEN #TwoWeeksAgo
AND #Today
AND sv2.id IS NULL
AND s.isActive = 1
AND stm.mallId = ${user['mallId']}
AND br.id != ${user['favBrand']['brandId']}
AND
NOT EXISTS (SELECT uess.saleID FROM dbo.UsersEmailsSalesSent uess WHERE uess.userID = ${user['userID']} and s.id=uess.saleID)
GROUP BY s.title, s.imageUrl, s.guid, br.title, s.id, stm.mallId
ORDER BY mostViewPeriod14Days DESC
I have a SQL query that I'm trying to optimize.
Is there a better way to avoid using subquery here?
Got a suggestion on using Row_number(),
posting this with some corrections
DECLARE #curdate DATETIME
SET #curdate = GETDATE()
SELECT DISTINCT
SIS.StudentID, StudentCoverage.StudentCoverageDataID,
Student.FirstName, Student.LastName,
Student.DateOfBirth, Student.Gender,
ASMT.AssessmentDate
FROM
SIS (NOLOCK)
INNER JOIN
SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
INNER JOIN
Assessment ASMT ON SIS.StudentID = ASMT.StudentId
INNER JOIN
StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
INNER JOIN
Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
INNER JOIN
Student (NOLOCK) ON Student.StudentID = SIS.StudentID
INNER JOIN
StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
AND StudentCoverageData.StudentCoverageDataID = (SELECT TOP 1 StudentCoverageData.StudentCoverageDataID
FROM StudentCoverage
INNER JOIN StudentCoverageData ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
WHERE StudentCoverage.StudentId = SIS.StudentID
AND StudentCoverageData.Active = 1
AND StudentCoverageData.EffectiveDate <= #curdate
AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > #curdate)
ORDER BY StudentCoverageData.AsOfDate DESC)
All Tables in your subquery is exists in inner join clause, so you could rewrite your query like this:
;WITH temps AS
(
DECLARE #curdate DATETIME = GETDATE()
SELECT
SIS.StudentID, StudentCoverage.StudentCoverageDataID,
Student.FirstName, Student.LastName,
Student.DateOfBirth, Student.Gender,
ASMT.AssessmentDate,
ROW_NUMBER() OVER (PARTITION BY StudentCoverageData.StudentCoverageDataID ORDER BY StudentCoverageData.AsOfDate) AS RowIndex
FROM
SIS (NOLOCK)
INNER JOIN
SISMaster (NOLOCK) ON SISMaster.SISID = SIS.SISID
INNER JOIN
StudentCoverage (NOLOCK) ON StudentCoverage.StudentID = SIS.StudentID
INNER JOIN
Organization (NOLOCK) ON StudentCoverage.OrgID = Organization.OrganizationID
INNER JOIN
Student (NOLOCK) ON Student.StudentID = SIS.StudentID
INNER JOIN
StudentCoverageData (NOLOCK) ON StudentCoverageData.StudentCoverageID = StudentCoverage.StudentCoverageID
WHERE StudentCoverageData.Active = 1
AND StudentCoverageData.EffectiveDate <= #curdate
AND (StudentCoverageData.ExitDate IS NULL OR StudentCoverageData.ExitDate > #curdate)
)
SELECT * FROM temps t
WHERE t.RowIndex = 1
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