I have a view in SQL server that i'm trying to convert to work in snowflake. The view uses two functions within it that are called to join onto another table.
I'm following steps provided by another user, but i'm getting lost somewhere in the middle and feel a little stuck.
Here is the query for the SQL Server view:
ALTER VIEW [proj].[pvw_PowerBI_ScrapList]
AS
SELECT
e.Name AS ProductionUnit,
temp.DateTime AS DateTime,
s.Reference AS Shift,
CONVERT(TIME, temp.DateTime) AS Time,
CONVERT(DATE, temp.DateTime - ISNULL((SELECT CAST(MIN(s_first.FromTimeOfDay) AS DateTime) FROM Shift s_first WHERE s_first.FromDay = s.FromDay AND s_first.ShiftCalendarID = s.ShiftCalendarID), CAST('6:00' AS DateTime))) AS ProductionDate,
temp.ScrapReason AS ScrapReason,
temp.Quantity AS ScrapQuantity,
'Manually Registered' AS RegistrationType
FROM (SELECT
CAST(SUM(sreg.ScrapQuantity) AS int) AS Quantity,
sreas.Name As ScrapReason,
DATEADD(MINUTE, 30 * (DATEPART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, 0, sreg.ScrapTime), 0)) AS DateTime,
srer.EquipmentID AS EquipmentID
FROM qms.ScrapRegistration sreg WITH (NOLOCK)
INNER JOIN qms.ScrapReason sreas WITH (NOLOCK) ON sreas.ID = sreg.ScrapReasonID -- creating CTE of this table
INNER JOIN WorkRequest wr WITH (NOLOCK) ON wr.ID = sreg.WorkRequestID -- CREATE CTE OF THIS TABLE
INNER JOIN SegmentRequirementEquipmentRequirement srer WITH (NOLOCK) ON srer.SegmentRequirementID = wr.SegmentRequirementID -- CREATE CTE OF THIS TABLE
GROUP BY DATEADD(MINUTE, 30 * (DATEPART(MINUTE, sreg.ScrapTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, 0, sreg.ScrapTime), 0)), srer.EquipmentID, sreas.Name) temp
INNER JOIN Equipment e WITH (NOLOCK) ON e.ID = temp.EquipmentID -- CREATE CTE OF THIS TABLE
INNER JOIN ShiftCalendar sc WITH (NOLOCK) ON sc.ID = dbo.cfn_GetEquipmentShiftCalendarID(e.ID, temp.DateTime) -- CREATE CTE OF THIS TABLE
INNER JOIN Shift s WITH (NOLOCK) ON s.ID = dbo.cfn_GetShiftIDFromDateTime(temp.DateTime, sc.ID) -- CREATE CTE OF THIS TABLE
UNION
SELECT
e.Name AS ProductionUnit,
temp.DateTime AS DateTime,
s.Reference AS Shift,
CONVERT(TIME, temp.DateTime) AS Time,
CONVERT(DATE, temp.DateTime - ISNULL((SELECT CAST(MIN(s_first.FromTimeOfDay) AS DateTime) FROM Shift s_first WHERE s_first.FromDay = s.FromDay AND s_first.ShiftCalendarID = s.ShiftCalendarID), CAST('6:00' AS DateTime))) AS ProductionDate,
temp.ScrapReason AS ScrapReason,
temp.Quantity AS ScrapQuantity,
'Auto Registered' AS RegistrationType
FROM (SELECT
SUM(ISNULL(asr.ScrapQuantity, 0)) AS Quantity,
sreas.Name As ScrapReason,
DATEADD(MINUTE, 30 * (DATEPART(MINUTE, asr.ScrapTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, 0, asr.ScrapTime), 0)) AS DateTime,
srer.EquipmentID AS EquipmentID
FROM proj.AutoScrapRegistration asr WITH (NOLOCK)
INNER JOIN qms.ScrapReason sreas WITH (NOLOCK) ON sreas.ID = asr.ScrapReasonID
INNER JOIN WorkRequest wr WITH (NOLOCK) ON wr.ID = asr.WorkRequestID
INNER JOIN SegmentRequirementEquipmentRequirement srer WITH (NOLOCK) ON srer.SegmentRequirementID = wr.SegmentRequirementID
GROUP BY DATEADD(MINUTE, 30 * (DATEPART(MINUTE, asr.ScrapTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, 0, asr.ScrapTime), 0)), srer.EquipmentID, sreas.Name) temp
INNER JOIN Equipment e WITH (NOLOCK) ON e.ID = temp.EquipmentID
INNER JOIN ShiftCalendar sc WITH (NOLOCK) ON sc.ID = dbo.cfn_GetEquipmentShiftCalendarID(temp.EquipmentID, temp.DateTime) -- the function is called here
INNER JOIN Shift s WITH (NOLOCK) ON s.ID = dbo.cfn_GetShiftIDFromDateTime(temp.DateTime, sc.ID) -- the function is called here
i'm ignoring the union for now to try and get something simply working.
The functions are highlighted in this post How to conver this SQL server Function into a CTE in snowflake
Here is what i have so far:
WITH table_ScrapRegistration (
Quantity
,ScrapReason
,DATETIME
,EquipmentID
,ScrapReasonID
,WorkRequestID
,SegmentRequirementID
)
AS (
SELECT CAST(SUM(sreg.ScrapQuantity) AS INT) AS Quantity
,sreas.Name AS ScrapReason
,DATEADD(MIN, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30)::INT, date_trunc('HOUR', sreg.ScrapTime)) AS DATETIME
,srer.EquipmentID AS EquipmentID
,sreas.ID AS ScrapReasonID
,wr.ID AS WorkRequestID
,srer.SegmentRequirementID AS SegmentRequirementID
FROM DB_BI_DEV.RAW_CPMS_LAG.ScrapRegistration sreg
INNER JOIN DB_BI_DEV.RAW_CPMS_LAG.ScrapReason sreas ON sreas.ID = sreg.ScrapReasonID -- CREATE CTE OF THIS TABLE
INNER JOIN DB_BI_DEV.RAW_CPMS_LAG.WorkRequest wr ON wr.ID = sreg.WorkRequestID -- CREATE CTE OF THIS TABLE
INNER JOIN DB_BI_DEV.RAW_CPMS_LAG.SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID -- CREATE CTE OF THIS TABLE
GROUP BY DATEADD(MIN, 30 * (DATE_PART(MINUTE, sreg.ScrapTime) / 30)::INT, date_trunc('HOUR', sreg.ScrapTime))
,srer.EquipmentID
,sreas.Name
,sreas.ID
,wr.ID
,srer.SegmentRequirementID
)
,table_scrapreason (
name
,ID
)
AS (
SELECT name
,ID
FROM DB_BI_DEV.RAW_CPMS_LAG.ScrapReason
)
,table_workrequest (
ID
,SegmentRequirementID
) -- this is from a join)
AS (
SELECT id
,SegmentRequirementID
FROM DB_BI_DEV.RAW_CPMS_LAG.WorkRequest
)
,table_SegmentRequirementEquipmentRequirement (
EquipmentID
,SegmentRequirementID
)
AS (
SELECT EquipmentID
,SegmentRequirementID
FROM DB_BI_DEV.RAW_CPMS_LAG.SegmentRequirementEquipmentRequirement
)
,table_equipment (
id
,name
,ParentEquipmentID
,ShiftCalendarEntityNumber
)
AS (
SELECT id
,name
,ParentEquipmentID
,ShiftCalendarEntityNumber
FROM DB_BI_DEV.RAW_CPMS_LAG.Equipment
)
,table_ShiftCalendar (
id,
entitynumber,
begindate,
enddate,
name,
PeriodInDays
)
AS (
SELECT id,
entitynumber,
begindate,
enddate,
name,
PeriodInDays
FROM DB_BI_DEV.RAW_CPMS_LAG.ShiftCalendar)
,table_shift (
ID
,Reference
,FromDay
)
AS -- this is from the temp table
(
SELECT ID
,Reference
,FromDay
FROM DB_BI_DEV.RAW_CPMS_LAG.shift
)
,temp_sub_select
AS (
SELECT sreg.Quantity AS Quantity
,sreas.name AS ScrapReason
,timeadd('minute', TRUNCATE (minute(sreg.DATETIME) / 30) * 30, date_trunc('hour', sreg.DATETIME)) AS DATETIME
,srer.EquipmentID AS EquipmentID
FROM table_ScrapRegistration sreg
INNER JOIN table_scrapreason sreas ON sreas.ID = sreg.ScrapReasonID -- CREATE CTE OF THIS TABLE
INNER JOIN table_workrequest wr ON wr.ID = sreg.WorkRequestID -- CREATE CTE OF THIS TABLE
INNER JOIN table_SegmentRequirementEquipmentRequirement srer ON srer.SegmentRequirementID = wr.SegmentRequirementID -- CREATE CTE OF THIS TABLE
GROUP BY sreg.Quantity
,sreas.name
,timeadd('minute', TRUNCATE (minute(sreg.DATETIME) / 30) * 30, date_trunc('hour', sreg.DATETIME))
,srer.EquipmentID
)
--select * from cte_GetEquipmentShiftCalendarID_part_a
--when i run this i get results
, cte_GetEquipmentShiftCalendarID_part_a
as (
WITH recursive rec_cte(id, parentequipmentid, shiftcalendarentitynumber) AS (
SELECT ID,
ParentEquipmentID,
ShiftCalendarEntityNumber
FROM table_equipment
UNION ALL
SELECT r.ID,
p.ParentEquipmentID,
p.ShiftCalendarEntityNumber
FROM rec_cte AS r
INNER JOIN table_equipment p ON p.ID = r.ParentEquipmentID
AND r.ShiftCalendarEntityNumber IS NULL
)
SELECT c.id,
sc.id AS shiftCalendarID,
sc.begindate,
sc.enddate
FROM rec_cte AS c
LEFT JOIN table_shiftcalendar AS sc ON sc.entitynumber = c.ShiftCalendarEntityNumber
WHERE shiftcalendarentitynumber IS NOT NULL
)
select * from cte_GetEquipmentShiftCalendarID_part_a
-- when i run this, i dont get any results.
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
I have two tables:
#Payments
#ControlNo
Each date represents TotalIncurred amount as of that date.
So if I want to get the last one (As Of today) , I'll simply use self join with MAX(PaymentID)
INNER JOIN
(SELECT ClaimID, MAX(PaymentID) AS MaxPaymentID
FROM #Payments mp
GROUP BY ClaimID) a ON a.ClaimID = p.ClaimID AND a.MaxPaymentID = p.PaymentID
But how would I also bring TotalIncurred as of 2019-05-22, and let's say as of '2019-05-08'. I dont need to pivot it for all dates, just for the last week, last month, last quarter etc.
The result should look like picture below on a right:
Would that be possible to do that in the same query?
Code sample:
DECLARE #Payments TABLE
(
ClaimID INT,
PaymentID INT,
TotalIncurred MONEY,
dateCreated DATE
)
INSERT INTO #Payments
VALUES (123, 1131215, 250, '2019-03-01'),
(123, 1132307, 130, '2019-05-18'),
(123, 1140297, 50, '2019-05-22'),
(123, 1155063, 80, '2019-06-30')
DECLARE #ControlNo TABLE (ClaimID int, ControlNo int)
INSERT INTO #ControlNo
VALUES (123, 54321)
--SELECT * FROM #Payments
--SELECT * FROM #ControlNo
SELECT
c.ControlNo,
SUM(TotalIncurred) AS TotalIncurred
FROM
#Payments p
INNER JOIN
(SELECT ClaimID, MAX(PaymentID) AS MaxPaymentID
FROM #Payments mp
GROUP BY ClaimID) a ON a.ClaimID = p.ClaimID AND a.MaxPaymentID = p.PaymentID
INNER JOIN
#ControlNo c ON c.ClaimID = p.ClaimID
GROUP BY
c.ControlNo
-- For the last week I'd use DateCreated <= GETDATE() -7
SELECT
c.ControlNo,
SUM(TotalIncurred) AS TotalIncurred
FROM
#Payments p
INNER JOIN
(SELECT ClaimID, MAX(PaymentID) AS MaxPaymentID
FROM #Payments mp
WHERE DateCreated < = GETDATE() - 7
GROUP BY ClaimID) a ON a.ClaimID = p.ClaimID AND a.MaxPaymentID = p.PaymentID
INNER JOIN
#ControlNo c ON c.ClaimID = p.ClaimID
GROUP BY
c.ControlNo
Current query:
Select
FORMAT(Tracking.[start],'dd-MM-yyy H:m:s') as [start],
FORMAT(Tracking.[deliver],'yyy-MM-dd') as dateSort,
FORMAT(Tracking.[deliver],'dd-MM-yyyy') as deliver,
RTrim(Tracking.[orderNumber]) as orderNumber,
Tracking.[tcpState] as oTcpState,
Tracking.[transport],
Tracking.[orderType],
(SELECT Cast(SUM(Cast(stations.estimatedTime as decimal(18,2))/60 ) as decimal(18,2)) FROM stations WHERE stations.orderNumber = Tracking.orderNumber) AS oEstimatedTime,
JSON_VALUE(Tracking.[orderObj],'$."0".Referenztext') as Referenztext,
JSON_VALUE(Tracking.[orderObj],'$."0".TotalSW') as TotalSW,
stations.[id],
FORMAT(stations.[startdate],'dd-MM-yyyy') as startdate,
FORMAT(stations.[enddate],'dd-MM-yyyy') as enddate,
stations.[tcpState],
stations.[name],
stations.[estimatedTime],
stations.[pieces],
stations.[piecesDone],
FORMAT(stations.[estimatedStart],'dd-MM-yyyy') as estimatedStart,
FORMAT(stations.[estimatedEnd],'dd-MM-yyyy') as estimatedEnd,
from Tracking left JOIN(
Select * from Stations left JOIN (
Select dummy.id as dId, dummy.orderNumber as dOrderNumber, SUM(dummy.elapsedTime) as elapsedTimeStationObj From (
select orderNumber, id, DATEDIFF(mi,startdate,ISNULL(enddate,GETDATE())) as elapsedTime FROM StationObj
) dummy group by dummy.orderNumber, dummy.id
) as stationObj
on Stations.orderNumber = stationObj.dOrderNumber and Stations.id = stationObj.dId
where stations.deleted=0
) as stations
on Tracking.orderNumber = stations.orderNumber where Tracking.tcpState != 3
Would like to have the SUM from elapsedTimeStationObj as well.
Tried to do it like this below the other (SELECT Cast(SUM(Cast(stations.estimatedTime....:
(SELECT Cast(SUM(Cast(stations.elapsedTimeStationObj as decimal(18,2))) as decimal(18,2)) FROM stations WHERE stations.orderNumber = Tracking.orderNumber) AS requiredTime,
but it is not possible because elapsedTimeStationObj is not a attribute from table Stations.
Use it as a subquery, and you can use as CTE to make it readable and reusble, like this:
WITH CTE1
AS
(
SELECT DUMMY.id AS dId
,DUMMY.orderNumber AS dOrderNumber
,SUM(DUMMY.elapsedTime) AS elapsedTimeStationObj
FROM (
SELECT orderNumber
,id
,DATEDIFF(mi, startdate, ISNULL(enddate, GETDATE())) AS elapsedTime
FROM StationObj
) DUMMY
GROUP BY DUMMY.orderNumber
,DUMMY.id
), CTE2
AS
(
SELECT orderNumber, Cast(SUM(Cast(stations.estimatedTime as decimal(18,2))/60 ) as decimal(18,2)) AS oEstimatedTime
FROM stations
GROUP BY stations.orderNumber
)
SELECT FORMAT(Tracking.[start], 'dd-MM-yyy H:m:s') AS [start]
,FORMAT(Tracking.[deliver], 'yyy-MM-dd') AS dateSort
,FORMAT(Tracking.[deliver], 'dd-MM-yyyy') AS deliver
,RTrim(Tracking.[orderNumber]) AS orderNumber
,Tracking.[tcpState] AS oTcpState
,Tracking.[transport]
,Tracking.[orderType]
,s2.oEstimatedTime AS oEstimatedTime
,JSON_VALUE(Tracking.[orderObj], '$."0".Referenztext') AS Referenztext
,JSON_VALUE(Tracking.[orderObj], '$."0".TotalSW') AS TotalSW
,stations.[id]
,FORMAT(stations.[startdate], 'dd-MM-yyyy') AS startdate
,FORMAT(stations.[enddate], 'dd-MM-yyyy') AS enddate
,stations.[tcpState]
,stations.[name]
,stations.[estimatedTime]
,stations.[pieces]
,stations.[piecesDone]
,FORMAT(stations.[estimatedStart], 'dd-MM-yyyy') AS estimatedStart
,FORMAT(stations.[estimatedEnd], 'dd-MM-yyyy') AS estimatedEnd
,
FROM Tracking
LEFT JOIN (
SELECT *
FROM Stations
LEFT JOIN CTE1 AS stationObj ON Stations.orderNumber = stationObj.dOrderNumber
AND Stations.id = stationObj.dId
WHERE stations.deleted = 0
) AS stations ON Tracking.orderNumber = stations.orderNumber
LEFT JOIN CTE2 s2 ON stations.orderNumber = s2.orderNumber
WHERE Tracking.tcpState != 3
Is it possible to update my a column in my table via subquery? the unique value is [ID] and [Date] How can I do this. So far I tried it like this but failed
UPDATE [dbo].[SCPL_EOD]
SET [CSP] = (SELECT
D.CSP FROM
(
SELECT PDT.CallID,SCP.*
,ROW_NUMBER() OVER(PARTITION BY SCP.[MIN],[ACCOUNT_NUMBER] ORDER BY SCP.[DATE_TIME] DESC) as [Row] FROM
(
SELECT *
FROM [SCPL].[dbo].[SCPL_EOD]
WHERE [SWITCH_RESULT] = 'ANSWERED'
AND [Date] BETWEEN #DateFrom AND #DateTo
) SCP
LEFT JOIN
(
SELECT
SUBSTRING([MIN],2,LEN([MIN])) as [MIN]
,CallID
,[Date]
,ROW_NUMBER() OVER(PARTITION BY [MIN],[PDcampaignBatch] ORDER BY PDTransaction.[SubmittedDateTime] DESC) as [Row]
FROM [Telemarketing].[dbo].[PDTransaction]
WHERE [Date] BETWEEN #DateFrom AND #DateTo
) PDT ON SCP.[MIN] = PDT.MIN AND SCP.[Date] = PDT.[DATE] AND PDT.[Row] = 1
)a
LEFT JOIN [Telemarketing].[dbo].[Disposition] d ON a.CallID = d.[Call ID]
WHERE a.[Row] = 1
) a
WHERE [MIN] =
The format you have is not correct for updating from a derived table, the format would be:
UPDATE A
SET A.Value = B.Value
FROM Table_A AS A
INNER JOIN
(
SELECT B.ID ,
B.Value
FROM Table_B AS B
) AS B ON B.ID = A.ID
WHERE A.ID = 1
But I would suggest using temp tables if that is a possibility, as it makes readability much easier.
I want to get data historical and the production. My stored procedure is as follows:
ALTER PROCEDURE [dbo].[pCaRptACInactivas](
#CodAsesor VARCHAR(15),
#CodOficina VARCHAR(4))
AS
SET NOCOUNT ON
DECLARE #CodArbolConta VARCHAR(25)
IF #CodOficina = '%'
SET #CodArbolConta = '%'
ELSE
SELECT #CodArbolConta = CodArbolConta + '%' FROM tClOficinas WHERE CodOficina LIKE #CodOficina
SELECT
tabACInactivas.CodOficina,
tabACInactivas.NomOficina,
tabACInactivas.NomAsesor,
MAX(tabACInactivas.CodPrestamo) CodPrestamo,
tabACInactivas.CodAsociacion,
tabACInactivas.NombreAsociacion,
MAX(tabACInactivas.Ciclo) AS Ciclo,
COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias,
MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--,
FROM ( SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaPrestamos.Ciclo, tCaPrCliente.CodUsuario, tCaPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaPrestamos Pr
INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaPrestamos.CodAsesor LIKE #CodAsesor AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
UNION ALL
SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaHPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaHPrestamos.Ciclo, tCaHPrCliente.CodUsuario, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaHPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaHPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaHPrestamos Pr
INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaHPrestamos.CodAsesor LIKE #CodAsesor AND tCaHPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
)tabACInactivas
GROUP BY tabACInactivas.CodAsociacion, tabACInactivas.NombreAsociacion, tabACInactivas.NomOficina, tabACInactivas.CodOficina, tabACInactivas.NomAsesor
I want the CantSocias column takes the most value of the Ciclo column, but not working
That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand. So I will go off of your last sentence:
I want the CantSocias column takes the most value of the Ciclo column,
but not working
Basically if you want to set a specific column to that, you can do something like this:
update YourTable
set CantSocias =
(
select max(Ciclo)
from YourOtherTable
)
-- here is where you can put a conditional WHERE clause
You may need to create a sub query to get the most value of Ciclo and join back to your query.
An example of what I mean is here:
create table #Product
(
ID int,
ProductName varchar(20)
)
insert into #Product(ID, ProductName)
select 1,'ProductOne'
union
select 2,'ProductTwo'
create table #ProductSale
(
ProductID int,
Number int,
SalesRegion varchar(20)
)
insert into #ProductSale(ProductID,Number,SalesRegion)
select 1,1500,'North'
union
select 1, 1200, 'South'
union
select 2,2500,'North'
union
select 2, 3200, 'South'
--select product sales region with the most sales
select * from #Product p
select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID
--combining
select
p.ID,
p.ProductName,
tp.Bestsale,
ps.SalesRegion
from
#Product p
inner join
(select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID
inner join
#ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number