Return one role per ID - sql-server-2008

I want to return only one role per employee(EmpID), that being the last employee to work on a specific task(FixEndDate). Below are mockup tables.
DECLARE #Problem TABLE
(
ProblemID INT
, ProblemDate DATETIME
, LogBy NVARCHAR(50)
)
INSERT INTO #Problem(ProblemID,ProblemDate,LogBy)
VALUES (1,CAST('2015-01-29 10:53:46.000'AS DATETIME),'Carl')
, (2,CAST('2015-01-21 10:53:46.000'AS DATETIME),'Paul')
, (3,CAST('2015-01-21 13:53:46.000'AS DATETIME),'Paul')
, (4,CAST('2015-01-21 15:53:46.000'AS DATETIME),'Paul')
DECLARE #Fix TABLE
(
FixID INT
, ProblemID INT
, EmpID INT
, FixStartDate DATETIME
, FixEndDate DATETIME
)
INSERT INTO #Fix(ProblemID, EmpID, FixStartDate, FixEndDate)
VALUES (1, 12, CAST('2015-02-02 10:53:46.000'AS DATETIME),CAST('2015-02-02 12:50:46.000'AS DATETIME))
, (1, 14, CAST('2015-02-03 10:53:46.000'AS DATETIME),CAST('2015-02-03 12:50:46.000'AS DATETIME))
, (2, 11, CAST('2015-02-04 10:53:46.000'AS DATETIME),CAST('2015-02-04 01:55:46.000'AS DATETIME))
, (2, 12, CAST('2015-02-04 05:56:46.000'AS DATETIME),CAST('2015-02-03 08:50:46.000'AS DATETIME))
, (3, 10, CAST('2015-02-04 07:53:46.000'AS DATETIME),CAST('2015-02-04 18:10:46.000'AS DATETIME))
, (3, 15, CAST('2015-02-05 10:53:46.000'AS DATETIME),CAST('2015-02-05 12:10:46.000'AS DATETIME))
, (3, 18, CAST('2015-02-05 11:53:46.000'AS DATETIME),CAST('2015-02-05 01:10:46.000'AS DATETIME))
, (4, 20, CAST('2015-02-07 12:53:46.000'AS DATETIME),CAST('2015-02-08 03:10:46.000'AS DATETIME))
, (4, 23, CAST('2015-02-08 11:53:46.000'AS DATETIME),CAST('2015-02-09 18:10:46.000'AS DATETIME))
, (4, 13, CAST('2015-02-10 16:53:46.000'AS DATETIME),CAST('2015-02-11 16:10:46.000'AS DATETIME))
I tried with:
SELECT f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
, f.FixEndDate
FROM #Problem AS p
INNER JOIN #Fix AS f
ON p.ProblemID = f.ProblemID
INNER JOIN (
SELECT f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
, MAX(f.FixEndDate) AS Fixed
FROM #Problem AS p
INNER JOIN #Fix AS f
ON p.ProblemID = f.ProblemID
GROUP BY f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
) AS d
ON d.EmpID = f.EmpID
AND d.Fixed = f.FixEndDate
ORDER BY FixEndDate DESC
Which is the way forward with this?

try
SELECT f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
, f.FixEndDate
FROM #Problem AS p
INNER JOIN (select * from (select * ,row_number() over (partition by ProblemID order by fixenddate desc) as rno from #Fix) t where rno=1) AS f
ON p.ProblemID = f.ProblemID

Related

How to conver this SQL server Function into a CTE in snowflake

I have two functions in SQL server that i'm trying to recreate in snowflake. i want to make it a CTE instead as i'm having many issues with it being a function (very picky about date parameters passed through)
I'm not quite thinking of it in the right way. So we pass two paramters through, a date and an int. and the function returns an INT value for us. I'm kind of "stuck".
--Function 1: Straight from SQL server
ALTER FUNCTION [dbo].[cfn_GetShiftIDFromDateTime] (
#dateTime datetime,
#shiftCalendarID int
)
RETURNS int
AS
BEGIN
DECLARE
#time time = CONVERT( time, #dateTime ),
#curDay int,
#prvDay int,
#shiftID int;
SELECT TOP 1
#shiftCalendarID = ID,
#curDay = DATEDIFF( dd, BeginDate, #dateTime ) % PeriodInDays + 1,
#prvDay = ( #curDay + PeriodInDays - 2 ) % PeriodInDays + 1
FROM ShiftCalendar
WHERE ID = #shiftCalendarID
OR ( #shiftCalendarID IS NULL
AND Name = 'Factory'
AND BeginDate <= #dateTime )
ORDER BY BeginDate DESC;
SELECT #shiftID = ID
FROM Shift
WHERE ShiftCalendarID = #shiftCalendarID
AND ( ( FromDay = #curDay AND FromTimeOfDay <= #time AND TillTimeOfDay > #time )
OR ( FromDay = #curDay AND FromTimeOfDay >= TillTimeOfDay AND FromTimeOfDay <= #time )
OR ( FromDay = #prvDay AND FromTimeOfDay >= TillTimeOfDay AND TillTimeOfDay > #time )
);
RETURN #shiftID;
END
--GO
I had help from a user writing this and was able to get this function written in snowflake and seems to be working properly. here it is below
--Function 1 -- Snowflake syntax, currently working
CREATE OR REPLACE FUNCTION DB_BI_DEV.RAW_CPMS_AAR.cfn_GetShiftIDFromDateTime (dateTime TIMESTAMP_NTZ(9), shiftCalendarID int)
RETURNS table (shiftID int)
AS
$$
WITH T0 (ShiftCalendarID, CurDay, PrvDay)
AS (
SELECT TOP 1
ID AS ShiftCalendarID,
DATEDIFF( day, BeginDate, dateTime ) % PeriodInDays + 1 AS CurDay,
( CurDay + PeriodInDays - 2 ) % PeriodInDays + 1 AS PrvDay
FROM RAW_CPMS_AAR.ShiftCalendar
WHERE ID = shiftCalendarID
OR ( shiftCalendarID IS NULL
AND Name = 'Factory'
AND BeginDate <= dateTime )
ORDER BY BeginDate DESC
),
T1 (TimeValue)
AS (
SELECT TIME_FROM_PARTS(
EXTRACT(HOUR FROM dateTime),
EXTRACT(MINUTE FROM dateTime),
EXTRACT(SECOND FROM dateTime))
)
SELECT ID as shiftID
FROM RAW_CPMS_AAR.Shift, T0, T1
WHERE Shift.ShiftCalendarID = T0.ShiftCalendarID
AND ( ( FromDay = T0.CurDay AND FromTimeOfDay <= T1.TimeValue AND TillTimeOfDay > T1.TimeValue )
OR ( FromDay = T0.CurDay AND FromTimeOfDay >= TillTimeOfDay AND FromTimeOfDay <= T1.TimeValue )
OR ( FromDay = T0.PrvDay AND FromTimeOfDay >= TillTimeOfDay AND TillTimeOfDay > T1.TimeValue )
)
$$
;
here is function 2:
--Function 2: Straight from SQL server
ALTER FUNCTION [dbo].[cfn_GetEquipmentShiftCalendarID] ( #equipmentID int, #date datetime )
RETURNS int
AS
BEGIN
IF #date IS NULL SET #date = GETDATE();
DECLARE
#shiftCalendarID int,
#endDate date;
WITH cte ( ID, ParentEquipmentID, ShiftCalendarEntityNumber ) AS (
SELECT ID, ParentEquipmentID, ShiftCalendarEntityNumber
FROM Equipment
WHERE ID = #equipmentID
UNION ALL
SELECT p.ID, p.ParentEquipmentID, p.ShiftCalendarEntityNumber
FROM cte
INNER JOIN Equipment p ON p.ID = cte.ParentEquipmentID AND cte.ShiftCalendarEntityNumber IS NULL
)
SELECT TOP 1 #shiftCalendarID = sc.ID, #endDate = sc.EndDate
FROM cte
INNER JOIN ShiftCalendar sc ON sc.EntityNumber = cte.ShiftCalendarEntityNumber
WHERE sc.BeginDate <= #date
ORDER BY
CASE WHEN EndDate IS NULL OR EndDate > #date THEN 1 ELSE 2 END, -- Prio on date range
sc.BeginDate DESC;
IF #shiftCalendarID IS NULL
BEGIN
-- Default to the last created calendar we find that started before the given time
SELECT TOP 1 #shiftCalendarID = ID
FROM ShiftCalendar
WHERE BeginDate < #date
ORDER BY BeginDate DESC;
END;
RETURN #shiftCalendarID; -- CASE WHEN #endDate IS NULL OR #endDate > #date THEN #shiftCalendarID END; -- Return NULL when no matching date range found?
END
GO
This one I was able to rewrite in snowflake but the if statement isnt working. I am not sure if snowflake function can use an if statement.
ALTER FUNCTION [dbo].[cfn_GetShiftIDFromDateTime] (
#dateTime datetime,
#shiftCalendarID int
)
RETURNS int
AS
BEGIN
DECLARE
#time time = CONVERT( time, #dateTime ),
#curDay int,
#prvDay int,
#shiftID int;
SELECT TOP 1
#shiftCalendarID = ID,
#curDay = DATEDIFF( dd, BeginDate, #dateTime ) % PeriodInDays + 1,
#prvDay = ( #curDay + PeriodInDays - 2 ) % PeriodInDays + 1
FROM ShiftCalendar
WHERE ID = #shiftCalendarID
OR ( #shiftCalendarID IS NULL
AND Name = 'Factory'
AND BeginDate <= #dateTime )
ORDER BY BeginDate DESC;
SELECT #shiftID = ID
FROM Shift
WHERE ShiftCalendarID = #shiftCalendarID
AND ( ( FromDay = #curDay AND FromTimeOfDay <= #time AND TillTimeOfDay > #time )
OR ( FromDay = #curDay AND FromTimeOfDay >= TillTimeOfDay AND FromTimeOfDay <= #time )
OR ( FromDay = #prvDay AND FromTimeOfDay >= TillTimeOfDay AND TillTimeOfDay > #time )
);
RETURN #shiftID;
END
--GO
so how are these functions used? i have a view which i was able to recreate in snowflake, but is missing the part that calls the function.
ALTER VIEW [proj].[pvw_PowerBI_ActualUnits]
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,
'Actual Units' AS ScrapReason,
temp.ScrapQuantity AS ScrapQuantity,
'Auto Registered' AS RegistrationType,
s.ID
FROM
(SELECT
vl.EquipmentID AS ProductionUnit,
DATEADD(MINUTE, 30 * (DATEPART(MINUTE, vl.BeginTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, 0, vl.BeginTime), 0)) AS DateTime,
SUM(vl.Quantity) AS ScrapQuantity
FROM oee.ValueLog vl WITH (NOLOCK)
INNER JOIN KPIInstance ki ON ki.ID = vl.KPIInstanceID AND ki.KPIDefinitionID LIKE 'COUNT-OUT:%'
GROUP BY DATEADD(MINUTE, 30 * (DATEPART(MINUTE, vl.BeginTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, 0, vl.BeginTime), 0)), vl.EquipmentID) temp
INNER JOIN Equipment e ON e.ID = temp.ProductionUnit
INNER JOIN Shift s ON s.ID = dbo.cfn_GetShiftIDFromDateTime(temp.DateTime, dbo.cfn_GetEquipmentShiftCalendarID(temp.ProductionUnit, temp.DateTime)) -- here is where the functions are called
i was able to rewrite this in snowflake for the most part minus calling the function.
SELECT
e.Name AS ProductionUnit,
temp.DateTime AS DateTime,
s.Reference AS Shift,
temp.DateTime::TIME 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,
IFNULL(dateadd(HOUR, - (HOUR(SELECT MIN(s_first.FromTimeOfDay)
FROM RAW_CPMS_AAR.Shift s_first WHERE s_first.FromDay = s.FromDay AND s_first.ShiftCalendarID = s.ShiftCalendarID)), temp.DateTime), (dateadd(HOUR, - 6, temp.DateTime))) AS ProductionDate ,
'Actual Units' AS ScrapReason,
temp.ScrapQuantity AS ScrapQuantity,
'Auto Registered' AS RegistrationType
FROM
(SELECT
vl.EquipmentID AS ProductionUnit,
DATEADD(MIN, 30 * (DATE_PART(MINUTE, vl.BeginTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, '0', vl.BeginTime), '0')) AS DateTime,
SUM(vl.Quantity) AS ScrapQuantity
FROM RAW_CPMS_AAR.ValueLog vl
INNER JOIN KPIInstance ki ON ki.ID = vl.KPIInstanceID AND ki.KPIDefinitionID LIKE 'COUNT-OUT:%'
GROUP BY DATEADD(MIN, 30 * (DATE_PART(MINUTE, vl.BeginTime) / 30), DATEADD(HOUR, DATEDIFF(HOUR, '0', vl.BeginTime), '0')), vl.EquipmentID) as temp, shiftcalendar_cte, RAW_CPMS_AAR.Equipment e, RAW_CPMS_AAR.Shift s
WHERE e.ID = temp.ProductionUnit
Now i dont know if there is a better way to do this, maybe a cte is better. i know functions are not resource friendly, i'm simply trying to recreate this. open to any ideas or help.
ok, some small translations:
DATEADD(HOUR, DATEDIFF(HOUR, 0, vl.BeginTime), 0)
is truncating to the hour, so is the same as
date_trunc('HOUR', vl.BeginTime)
that dateadd thus is:
select column1
,date_trunc('hour', column1) as t_hour
,truncate(minute(column1)/30)*30
,timeadd('minute', truncate(minute(column1)/30)*30, date_trunc('hour', column1)) as datetime
from values
('2022-11-14 13:26:01'::timestamp_ntz),
('2022-11-14 12:34:01'::timestamp_ntz);
COLUMN1
T_HOUR
TRUNCATE(MINUTE(COLUMN1)/30)*30
DATETIME
2022-11-14 13:26:01.000
2022-11-14 13:00:00.000
0
2022-11-14 13:00:00.000
2022-11-14 12:34:01.000
2022-11-14 12:00:00.000
30
2022-11-14 12:30:00.000
So moving that sub-select that you alias as temp into a CTE, and get that "working"
WITH table_oee_valuelog(equipmentid, begintime, quantity, kpiinstanceid) as (
select * from values
(1, '2022-11-14 13:26:01'::timestamp_ntz, 10, 100),
(1, '2022-11-14 13:26:01'::timestamp_ntz, 11, 100),
(1, '2022-11-14 13:34:01'::timestamp_ntz, 12, 100)
), table_kpiinstance(id, kpidefinitionid) as (
select * from values
(100, 'COUNT-OUT:extra stuff')
)--, temp_sub_select as (
SELECT
vl.equipmentid as productionunit,
timeadd('minute', truncate(minute(vl.BeginTime)/30)*30, date_trunc('hour', vl.BeginTime)) as datetime,
SUM(vl.quantity) AS scrapquantity
FROM table_oee_valuelog as vl
INNER JOIN table_kpiinstance as ki
ON ki.ID = vl.KPIInstanceID
AND ki.KPIDefinitionID LIKE 'COUNT-OUT:%'
GROUP BY 1,2
;)
PRODUCTIONUNIT
DATETIME
SCRAPQUANTITY
1
2022-11-14 13:00:00.000
21
1
2022-11-14 13:30:00.000
12
implementing cfn_GetEquipmentShiftCalendarID
so if we extend our table data a bit more we can take a first crack at cfn_GetEquipmentShiftCalendarID like:
WITH table_oee_valuelog(equipmentid, begintime, quantity, kpiinstanceid) as (
select * from values
(1, '2022-11-14 13:26:01'::timestamp_ntz, 10, 100),
(1, '2022-11-14 13:26:01'::timestamp_ntz, 11, 100),
(1, '2022-11-14 13:34:01'::timestamp_ntz, 12, 100)
), table_kpiinstance(id, kpidefinitionid) as (
select * from values
(100, 'COUNT-OUT:extra stuff')
), table_equipment(id, name, parentequipmentid, shiftcalendarentitynumber) as (
select * from values
(1,'equipment one', 2, null),
(2,'equipment two', null, 80),
(3,'equipment three', 4, 81),
(4,'equipment four', null, 82)
), table_shift(id, shiftcalendarid, reference) as (
select * from values
(1001, 9001, 'a')
), table_shiftcalendar(id, entitynumber, begindate, enddate) as (
select * from values
(699, 80, '2021-01-01'::date, '2021-12-31'::date),
(700, 80, '2022-01-01'::date, '2022-12-31'::date),
--(701, 81, '2022-02-01'::date, '2022-11-30'::date),
(702, 82, '2022-10-01'::date, '2022-11-15'::date)
), cte_GetEquipmentShiftCalendarID/*(id, shiftCalendarID)*/ 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 * from rec_cte as c
left join table_shiftcalendar as sc
on sc.entitynumber = c.ShiftCalendarEntityNumber
where shiftcalendarentitynumber is not null
qualify row_number() over (partition by c.id order by sc.begindate desc ) = 1
)
select * from cte_GetEquipmentShiftCalendarID;
This is missing the #date based filters and the catch all, as to product the "latest" all bit of equipment, cannot be done yet.
ID
PARENTEQUIPMENTID
SHIFTCALENDARENTITYNUMBER
ID_2
ENTITYNUMBER
BEGINDATE
ENDDATE
1
80
700
80
2022-01-01
2022-12-31
2
80
700
80
2022-01-01
2022-12-31
3
4
81
4
82
702
82
2022-10-01
2022-11-15
so we need to weave this current data, with the temp table, how convenient we made it a CTE already...
so the next partial step is:
WITH table_oee_valuelog(equipmentid, begintime, quantity, kpiinstanceid) as (
select * from values
(1, '2022-11-14 13:26:01'::timestamp_ntz, 10, 100),
(1, '2022-11-14 13:26:01'::timestamp_ntz, 11, 100),
(1, '2022-11-14 13:34:01'::timestamp_ntz, 12, 100),
(2, '2022-11-14 13:34:01'::timestamp_ntz, 20, 100),
(3, '2022-11-14 13:34:01'::timestamp_ntz, 30, 100),
(4, '2022-11-14 13:34:01'::timestamp_ntz, 44, 100)
), table_kpiinstance(id, kpidefinitionid) as (
select * from values
(100, 'COUNT-OUT:extra stuff')
), table_equipment(id, name, parentequipmentid, shiftcalendarentitynumber) as (
select * from values
(1,'equipment one', 2, null),
(2,'equipment two', null, 80),
(3,'equipment three', 4, 81),
(4,'equipment four', null, 82)
), table_shift(id, shiftcalendarid, reference) as (
select * from values
(1001, 9001, 'a')
), table_shiftcalendar(id, entitynumber, begindate, enddate) as (
select * from values
(699, 80, '2021-01-01'::date, '2021-12-31'::date),
(700, 80, '2022-01-01'::date, '2022-12-31'::date),
(701, 80, '2023-01-01'::date, '2023-12-31'::date),
--(701, 81, '2022-02-01'::date, '2022-11-30'::date),
(702, 82, '2022-10-01'::date, '2022-11-15'::date)
), temp_sub_select as (
SELECT
vl.equipmentid as productionunit,
timeadd('minute', truncate(minute(vl.BeginTime)/30)*30, date_trunc('hour', vl.BeginTime)) as datetime,
SUM(vl.quantity) AS scrapquantity
FROM table_oee_valuelog as vl
INNER JOIN table_kpiinstance as ki
ON ki.ID = vl.KPIInstanceID
AND ki.KPIDefinitionID LIKE 'COUNT-OUT:%'
GROUP BY 1,2
), cte_GetEquipmentShiftCalendarID_part_a/*(id, shiftCalendarID)*/ 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
)--, last_calendar_per_equipment as (
select *
,iff(c.enddate is null or c.enddate > t.datetime, 1, 2) as order_a
,row_number() over (partition by t.productionunit, t.datetime order by order_a, c.begindate desc) as rn
from temp_sub_select as t
left join cte_GetEquipmentShiftCalendarID_part_a as c
on t.productionunit = c.id
and c.begindate <= t.datetime
;)
this gives:
PRODUCTIONUNIT
DATETIME
SCRAPQUANTITY
ID
SHIFTCALENDARID
BEGINDATE
ENDDATE
ORDER_A
RN
1
2022-11-14 13:00:00.000
21
1
700
2022-01-01
2022-12-31
1
1
1
2022-11-14 13:00:00.000
21
1
699
2021-01-01
2021-12-31
2
2
1
2022-11-14 13:30:00.000
12
1
700
2022-01-01
2022-12-31
1
1
1
2022-11-14 13:30:00.000
12
1
699
2021-01-01
2021-12-31
2
2
2
2022-11-14 13:30:00.000
20
2
700
2022-01-01
2022-12-31
1
1
2
2022-11-14 13:30:00.000
20
2
699
2021-01-01
2021-12-31
2
2
3
2022-11-14 13:30:00.000
30
1
1
4
2022-11-14 13:30:00.000
44
4
702
2022-10-01
2022-11-15
1
1
last step of this function can be handled with this CTE which we can join to the prior results, and take if the prior results are null.
select
t.datetime,
sc.id
from (
select distinct datetime
from temp_sub_select
) as t
join table_shiftcalendar as sc
on sc.begindate <= t.datetime
qualify row_number() over (partition by t.datetime order by sc.begindate desc) = 1
weave those together and a little data change:
WITH table_oee_valuelog(equipmentid, begintime, quantity, kpiinstanceid) as (
select * from values
(1, '2022-11-14 13:26:01'::timestamp_ntz, 10, 100),
(1, '2022-11-14 13:26:01'::timestamp_ntz, 11, 100),
(1, '2022-11-14 13:34:01'::timestamp_ntz, 12, 100),
(2, '2022-11-14 13:34:01'::timestamp_ntz, 20, 100),
(3, '2022-11-14 13:34:01'::timestamp_ntz, 30, 100),
(4, '2022-11-14 13:34:01'::timestamp_ntz, 44, 100)
), table_kpiinstance(id, kpidefinitionid) as (
select * from values
(100, 'COUNT-OUT:extra stuff')
), table_equipment(id, name, parentequipmentid, shiftcalendarentitynumber) as (
select * from values
(1,'equipment one', 2, null),
(2,'equipment two', null, 80),
(3,'equipment three', 4, 81),
(4,'equipment four', null, 82)
), table_shift(id, shiftcalendarid, reference) as (
select * from values
(1001, 9001, 'a')
), table_shiftcalendar(id, entitynumber, begindate, enddate) as (
select * from values
(699, 80, '2021-01-01'::date, '2021-12-31'::date),
(700, 80, '2022-01-01'::date, '2022-12-31'::date),
(701, 80, '2023-01-01'::date, '2023-12-31'::date),
--(701, 81, '2022-02-01'::date, '2022-11-30'::date),
(702, 82, '2022-10-01'::date, '2022-11-15'::date),
(703, 89, '2022-11-01'::date, '2022-11-15'::date)
), temp_sub_select as (
SELECT
vl.equipmentid as productionunit,
timeadd('minute', truncate(minute(vl.BeginTime)/30)*30, date_trunc('hour', vl.BeginTime)) as datetime,
SUM(vl.quantity) AS scrapquantity
FROM table_oee_valuelog as vl
INNER JOIN table_kpiinstance as ki
ON ki.ID = vl.KPIInstanceID
AND ki.KPIDefinitionID LIKE 'COUNT-OUT:%'
GROUP BY 1,2
), cte_GetEquipmentShiftCalendarID_part_a/*(id, shiftCalendarID)*/ 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
), cte_GetEquipmentShiftCalendarID_part_b as (
select t.productionunit,
t.org_datetime,
t.datetime,
c.shiftCalendarID
from (
select
productionunit,
datetime as org_datetime,
nvl(datetime, CURRENT_DATE) as datetime /* handle the null case from the T-SQL */
from temp_sub_select
) as t
left join cte_GetEquipmentShiftCalendarID_part_a as c
on t.productionunit = c.id
and c.begindate <= t.datetime
qualify row_number() over (partition by t.productionunit, t.datetime
order by iff(c.enddate is null or c.enddate > t.datetime, 1, 2), c.begindate desc) = 1
), max_shiftCalendar_per_datetime as (
select
t.datetime,
sc.id
from (
select distinct nvl(datetime, CURRENT_DATE) as datetime
from temp_sub_select
) as t
join table_shiftcalendar as sc
on sc.begindate <= t.datetime
qualify row_number() over (partition by t.datetime order by sc.begindate desc) = 1
)--, last_calendar_per_equipment as (
select
a.productionunit
,a.org_datetime
,a.shiftCalendarID, b.id
,nvl(a.shiftCalendarID, b.id) as shiftCalendarID
from cte_GetEquipmentShiftCalendarID_part_b as a
join max_shiftCalendar_per_datetime as b
on a.datetime = b.datetime
;)
gives:
PRODUCTIONUNIT
ORG_DATETIME
SHIFTCALENDARID
ID
SHIFTCALENDARID_2
1
2022-11-14 13:00:00.000
700
703
700
1
2022-11-14 13:30:00.000
700
703
700
2
2022-11-14 13:30:00.000
700
703
700
3
2022-11-14 13:30:00.000
703
703
4
2022-11-14 13:30:00.000
702
703
702
Mostly Complete answer:
So I striped ProductionDate and the two fixed string from my answer but:
--CREATE VIEW proj.pvw_PowerBI_ActualUnits
WITH table_oee_valuelog(equipmentid, begintime, quantity, kpiinstanceid) as (
select * from values
(1, '2022-11-14 13:26:01'::timestamp_ntz, 10, 100),
(1, '2022-11-14 13:26:01'::timestamp_ntz, 11, 100),
(1, '2022-11-14 13:34:01'::timestamp_ntz, 12, 100),
(2, '2022-11-14 13:34:01'::timestamp_ntz, 20, 100),
(3, '2022-11-14 13:34:01'::timestamp_ntz, 30, 100),
(4, '2022-11-14 13:34:01'::timestamp_ntz, 44, 100)
), table_kpiinstance(id, kpidefinitionid) as (
select * from values
(100, 'COUNT-OUT:extra stuff')
), table_equipment(id, name, parentequipmentid, shiftcalendarentitynumber) as (
select * from values
(1,'equipment one', 2, null),
(2,'equipment two', null, 80),
(3,'equipment three', 4, 81),
(4,'equipment four', null, 82)
), table_shift(id, shiftcalendarid, reference, FromDay, FromTimeOfDay, TillTimeOfDay) as (
select * from values
(1001, 700, 'a', 8, '06:00'::time,'18:00'::time),
(1001, 702, 'a', 5, '06:00'::time,'18:00'::time),
(1001, 703, 'a', 4, '06:00'::time,'18:00'::time)
), table_shiftcalendar(id, entitynumber, begindate, enddate, name, PeriodInDays) as (
select * from values
(699, 80, '2021-01-01'::date, '2021-12-31'::date, 'Factory', 10),
(700, 80, '2022-01-01'::date, '2022-12-31'::date, 'Factory', 10),
(701, 80, '2023-01-01'::date, '2023-12-31'::date, 'Factory', 10),
--(701, 81, '2022-02-01'::date, '2022-11-30'::date, 'Factory', 10),
(702, 82, '2022-10-01'::date, '2022-11-15'::date, 'Factory', 10),
(703, 89, '2022-11-01'::date, '2022-11-15'::date, 'Factory', 10)
), temp_sub_select as (
SELECT
vl.equipmentid as productionunit,
timeadd('minute', truncate(minute(vl.BeginTime)/30)*30, date_trunc('hour', vl.BeginTime)) as datetime,
SUM(vl.quantity) AS scrapquantity
FROM table_oee_valuelog as vl
INNER JOIN table_kpiinstance as ki
ON ki.ID = vl.KPIInstanceID
AND ki.KPIDefinitionID LIKE 'COUNT-OUT:%'
GROUP BY 1,2
), 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
), cte_GetEquipmentShiftCalendarID_part_b as (
select t.productionunit,
t.org_datetime,
t.datetime,
c.shiftCalendarID
from (
select
productionunit,
datetime as org_datetime,
nvl(datetime, CURRENT_DATE) as datetime /* handle the null case from the T-SQL */
from temp_sub_select
) as t
left join cte_GetEquipmentShiftCalendarID_part_a as c
on t.productionunit = c.id
and c.begindate <= t.datetime
qualify row_number() over (partition by t.productionunit, t.datetime
order by iff(c.enddate is null or c.enddate > t.datetime, 1, 2), c.begindate desc) = 1
), max_shiftCalendar_per_datetime as (
select
t.datetime,
sc.id
from (
select distinct nvl(datetime, CURRENT_DATE) as datetime
from temp_sub_select
) as t
join table_shiftcalendar as sc
on sc.begindate <= t.datetime
qualify row_number() over (partition by t.datetime order by sc.begindate desc) = 1
), last_calendar_per_equipment as (
select
a.productionunit
,a.org_datetime
,nvl(a.shiftCalendarID, b.id) as shiftCalendarID
from cte_GetEquipmentShiftCalendarID_part_b as a
join max_shiftCalendar_per_datetime as b
on a.datetime = b.datetime
), cfn_GetShiftIDFromDateTime as (
with t0 as (
select
x.productionunit
,x.org_datetime
,x.org_datetime::time as org_time
,x.ShiftCalendarID
,DATEDIFF( day, BeginDate, x.org_datetime ) % PeriodInDays + 1 AS CurDay
,( CurDay + PeriodInDays - 2 ) % PeriodInDays + 1 AS PrvDay
from last_calendar_per_equipment as x
join table_shiftcalendar as sc
where sc.id = x.shiftCalendarID
OR ( x.shiftCalendarID IS NULL
AND sc.Name = 'Factory'
AND sc.BeginDate <= x.org_datetime )
QUALIFY row_number() over (partition by x.productionunit, x.org_datetime order by sc.begindate desc) = 1
)
SELECT
s.id
,s.reference
,productionunit
,org_datetime
,s.ShiftCalendarID
,s.FromDay, s.FromTimeOfDay, s.TillTimeOfDay, T0.CurDay, t0.org_time
FROM table_shift as s, T0
WHERE s.ShiftCalendarID = T0.ShiftCalendarID
AND ( ( s.FromDay = T0.CurDay AND s.FromTimeOfDay <= t0.org_time AND s.TillTimeOfDay > t0.org_time )
OR ( s.FromDay = T0.CurDay AND s.FromTimeOfDay >= s.TillTimeOfDay AND s.FromTimeOfDay <= t0.org_time )
OR ( s.FromDay = T0.PrvDay AND s.FromTimeOfDay >= s.TillTimeOfDay AND s.TillTimeOfDay > t0.org_time )
)
)
SELECT
e.name AS productionunit,
temp.datetime AS datetime,
s.reference AS shift,
temp.DateTime::time AS Time,
temp.ScrapQuantity AS ScrapQuantity,
s.ID
FROM temp_sub_select as temp
INNER JOIN table_equipment e
ON e.ID = temp.ProductionUnit
INNER JOIN cfn_GetShiftIDFromDateTime s
ON s.productionunit = temp.ProductionUnit
and temp.datetime = s.org_datetime
as far as I can follow, does what your functions do, and unrolls the correlated query, as that would never work in Snowflake.
PRODUCTIONUNIT
DATETIME
SHIFT
TIME
SCRAPQUANTITY
ID
equipment one
2022-11-14 13:00:00.000
a
13:00:00
21
1001
equipment one
2022-11-14 13:30:00.000
a
13:30:00
12
1001
equipment two
2022-11-14 13:30:00.000
a
13:30:00
20
1001
equipment three
2022-11-14 13:30:00.000
a
13:30:00
30
1001
equipment four
2022-11-14 13:30:00.000
a
13:30:00
44
1001
Not so bad for five hours work...

How can I rewrite this to remove select statement joins?

As it is now each time I am selecting from Bill in my actual database I am searching over 1 million rows. There has to be a better way to write this query, but I haven't been able to figure it out. There has to be some way I can write this that doesn't join using the select statements.
If you notice I have some form of this join three seperate times. What should I do to remove this join?
join
(
select b.year
, sum(bli.amount) amt
from Bill b
join BillLine bli
on bli.bill_id = b.id
where bli.payment = 0
and bli.refund = 0
and bli.type = 3
group
by b.year
) org
on org.year = b.year
select b.Year,
Round(case when b.year = (select collectoryear -1 from Entity) then 0 else beg.amt end,2) Beginning,
Round(case when b.year >= (select collectoryear -1 from Entity) then ifnull(org.amt,0) else 0 end,2) Additions,
Round(case when b.year = (select collectoryear -1 from Entity) then 0 else beg.amt end + case when b.year >= (select collectoryear -1 from Entity) then ifnull(org.amt,0) else 0 end - ending.amt ,2) Collections,
Round(ending.amt,2) Ending
from Bill b
left join Levy l on l.year = b.year
join Entity e on b.year = e.year
join( select b.year, sum(bli.amount) amt from Bill b join BillLine bli on bli.bill_id = b.id where bli.payment = 0 and bli.refund = 0 and bli.type = 3 group by b.year) org on org.year = b.year
join( select b.year, sum(bli.amount) amt from Bill b join BillLine bli on bli.bill_id = b.id where bli.type = 2 group by b.year ) beg on beg.year = b.year
join( select b.year, sum(bli.amount) amt from Bill b join BillLine bli on bli.bill_id = b.id where bli.type = 2 group by b.year ) ending on ending.year = b.year
where b.year > (select collectoryear -11 from Entity)
and b.year < (select collectoryear from Entity)
group by b.year
order by Year desc ;
Here is the db-fiddle databases
create table Bill
( id varchar(20) PRIMARY KEY
, year varchar(20) FOREIGN KEY
);
Insert into Bill (id, year) values
(1, 2020),
(2, 2020),
(3, 2020),
(4, 2019),
(5, 2019),
(6, 2018),
(7, 2017),
(8, 2016),
(9, 2015),
(10, 2013);
create table BillLine
( id varchar(20) PRIMARY KEY
, bill_id varchar(20) FOREIGN KEY
, amount varchar(20)
, refund varchar(20)
, payment varchar(20)
, type varchar(20)
);
Insert into BillLine (id, bill_id, amount, refund, payment, type) values
(1, 10, 100.00, 0, 0, 3),
(2, 9, 250.00, 1, 1, 5),
(3, 8, 102.00, 0, 0, 3),
(4, 7, 85.00, 1, 1, 5),
(5, 6, 20.00, 0, 0, 3),
(6, 5, 43.75, 0, 1, 2),
(7, 4, 22.22, 0, 0, 3),
(8, 3, 125.25, 0, 1, 2),
(9, 2, 77.70, 0, 0, 3),
(10, 1, 100.75, 1, 1, 5);
create table Entity
( id varchar(20) PRIMARY KEY
, collectoryear varchar(20)
, year varchar(20)
);
Insert into Entity (id, collectoryear, year) values (1, 2021, 2020);
create table Levy
( id varchar(20) PRIMARY KEY, county varchar(20), year varchar(20)
);
Insert into Levy (id, county, year) values (1, null, null);

SSRS subscription migration

I have several SSRS subscriptions built but my company just did a domain conversion and those subscriptions are all saved to my old domain login. This had led to a few questions:
1) Is there a way to move all those subscriptions to my new account?
2) Is it possible to setup the subscriptions to be viewable by multiple users?
3) Is it possible to setup the subscriptions to be editable by multiple users?
We are using SSRS 2012
I had to do this a few times at my last organization.
To answer your first question, I use the script below to update the subscription and report owners. I use SQL Command Mode to easily change to different servers. It is also necessary for the variables.
To turn on SQL Command Mode in SSMS, on the menu bar click on Query | SQLCMD Mode
Note: The NewUser must already exist in dbo.Users and you must have UPDATE permission on the dbo.ReportServer database to use this script.
/*------------------------------------------------------------------------------+
| Purpose: To Update the owner of deployed reports and subscriptions
| Note: SQLCmdMode Script
+--------------------------------------------------------------------------------
*/
:setvar _server "***YourServerNameHere***"
:setvar _database "ReportServer"
:connect $(_server)
USE [$(_database)];
GO
:SETVAR OldUser "DOMAIN\OldUserName"
:SETVAR NewUser "DOMAIN\NewUserName"
SET XACT_ABORT ON
BEGIN TRANSACTION
PRINT '====================================================================='
PRINT 'Update subscriptions...'
PRINT '====================================================================='
;WITH
new_owner
AS
(
SELECT [UserID], [UserName] FROM dbo.[Users] WHERE [UserName] = N'$(NewUser)'
)
,
subscription_source
AS
(
SELECT
s.[Report_OID]
, [OldOwner] = ou.[UserName]
, [OldOwnerID] = ou.[UserID]
, [NewOwner] = nu.[UserName]
, [NewOwnerID] = nu.[UserID]
FROM
dbo.[Subscriptions] AS s
INNER JOIN dbo.[Users] AS ou ON ou.[UserID] = s.[OwnerID]
, new_owner AS nu
WHERE
1=1
AND ou.[UserName] = N'$(OldUser)'
)
--SELECT * FROM subscription_source
MERGE dbo.Subscriptions AS T
USING subscription_source AS S ON T.[Report_OID] = S.[Report_OID]
WHEN MATCHED
THEN UPDATE SET
T.[OwnerID] = S.[NewOwnerID]
OUTPUT ##ServerName AS ServerName, db_name() AS DatabaseName, $action, inserted.*, deleted.*;
PRINT '====================================================================='
PRINT 'Update report created by...'
PRINT '====================================================================='
;WITH
new_owner
AS
(
SELECT [UserID], [UserName] FROM dbo.[Users] WHERE [UserName] = N'$(NewUser)'
)
,
report_list_source
AS
(
SELECT
c.[ItemID]
, c.[Name]
, [OldOwner] = ou.[UserName]
, [OldOwnerID] = ou.[UserID]
, [NewOwner] = nu.[UserName]
, [NewOwnerID] = nu.[UserID]
FROM
dbo.[Catalog] AS c
INNER JOIN dbo.[Users] AS ou ON ou.[UserID] = c.[CreatedById]
, new_owner AS nu
WHERE
1=1
AND ou.[UserName] = N'$(OldUser)'
AND c.[Type] = 2
)
--SELECT * FROM report_list_source
MERGE dbo.[Catalog] AS T
USING report_list_source AS S ON T.[ItemID] = S.[ItemID]
WHEN MATCHED
THEN UPDATE SET
T.[CreatedById] = S.[NewOwnerID]
OUTPUT ##ServerName AS ServerName, db_name() AS DatabaseName, $action, inserted.*, deleted.*;
PRINT '====================================================================='
PRINT 'Update report modified by...'
PRINT '====================================================================='
;WITH
new_owner
AS
(
SELECT [UserID], [UserName] FROM dbo.[Users] WHERE [UserName] = N'$(NewUser)'
)
,
report_list_source
AS
(
SELECT
c.[ItemID]
, c.[Name]
, [OldOwner] = ou.[UserName]
, [OldOwnerID] = ou.[UserID]
, [NewOwner] = nu.[UserName]
, [NewOwnerID] = nu.[UserID]
FROM
dbo.[Catalog] AS c
INNER JOIN dbo.[Users] AS ou ON ou.[UserID] = c.[ModifiedById]
, new_owner AS nu
WHERE
1=1
AND ou.[UserName] = N'$(OldUser)'
AND c.[Type] = 2
)
--SELECT * FROM report_list_source
MERGE dbo.[Catalog] AS T
USING report_list_source AS S ON T.[ItemID] = S.[ItemID]
WHEN MATCHED
THEN UPDATE SET
T.[ModifiedById] = S.[NewOwnerID]
OUTPUT ##ServerName AS ServerName, db_name() AS DatabaseName, $action, inserted.*, deleted.*;
PRINT '******* ROLLBACK TRANSACTION ******* ';
ROLLBACK TRANSACTION;
--PRINT '******* COMMIT TRANSACTION ******* ';
--COMMIT TRANSACTION;
PRINT '====================================================================='
PRINT 'Finished...'
PRINT '====================================================================='
To answer your second question, I wrote a report to view all the subscriptions. Below is the report SQL. Here is the rdl file if you just want to download that.
/*'------------------------------------------------------------------------------------------------------------------
| Purpose: Schedule Of Recurring Report Subscriptions
| Note: SQLCmdMode Script
'--------------------------------------------------------------------------------------------------------------------
DECLARE #all_value AS VARCHAR(100)
DECLARE #ReportFolder AS VARCHAR(100)
DECLARE #ReportName AS VARCHAR(100)
DECLARE #EmailLike AS VARCHAR(100)
DECLARE #ModifiedBy AS VARCHAR(50)
DECLARE #SubcriptionOwner AS VARCHAR(50)
DECLARE #SubscriptionStatus AS VARCHAR(1)
DECLARE #EventStatus AS VARCHAR(50)
DECLARE #Current AS VARCHAR(50)
DECLARE #LastSubscriptionDate AS DATETIME
SET #all_value = '<ALL>'
SET #ReportFolder = '<ALL>'
SET #ReportName = '<ALL>'
SET #EmailLike = NULL
SET #ModifiedBy = NULL
SET #SubcriptionOwner = NULL
SET #SubscriptionStatus = 'A' -- Y=Sent, N=Fail, A=All
SET #EventStatus = '<ALL>' -- status from ReportServer.dbo.ExecutionLog
SET #Current = '<ALL>'
SET #LastSubscriptionDate = NULL --getdate()-1
*/
;WITH
report_users
AS
(
SELECT [UserID], [UserName], [SimpleUserName] = UPPER(RIGHT([UserName],(LEN([UserName])-CHARINDEX('\',[UserName])))) FROM dbo.[Users]
)
,
report_catalog
AS
(
SELECT
c.[ItemID]
, c.[CreatedById]
, c.[ModifiedById]
, c.[Type]
, c.[Name]
, c.[Description]
, c.[Parameter]
, [ReportCreationDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), c.[CreationDate], 13))
, [ReportModifiedDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), c.[ModifiedDate], 13))
, [ReportFolder] =
CASE
WHEN c.[Path] = '/' + c.[Name] THEN ''
ELSE SUBSTRING(c.[Path], 2, Len(c.[Path])-Len(c.[Name])-2)
END
, [ReportPath] = c.[Path]
, [UrlPath] = 'http://' + Host_Name() + '/Reports/Pages/Folder.aspx?ItemPath=%2f'
, [ReportDefinition] = CONVERT(VARCHAR(MAX),CONVERT(VARBINARY(MAX), c.[Content]))
FROM
dbo.[Catalog] AS c
WHERE c.[Type] = 2
)
,
subscription_days
AS
(
SELECT tbl.* FROM (VALUES
( 'DaysOfMonth', 1, '1')
, ( 'DaysOfMonth', 2, '2')
, ( 'DaysOfMonth', 4, '3')
, ( 'DaysOfMonth', 8, '4')
, ( 'DaysOfMonth', 16, '5')
, ( 'DaysOfMonth', 32, '6')
, ( 'DaysOfMonth', 64, '7')
, ( 'DaysOfMonth', 128, '8')
, ( 'DaysOfMonth', 256, '9')
, ( 'DaysOfMonth', 512, '10')
, ( 'DaysOfMonth', 1024, '11')
, ( 'DaysOfMonth', 2048, '12')
, ( 'DaysOfMonth', 4096, '13')
, ( 'DaysOfMonth', 8192, '14')
, ( 'DaysOfMonth', 16384, '15')
, ( 'DaysOfMonth', 32768, '16')
, ( 'DaysOfMonth', 65536, '17')
, ( 'DaysOfMonth', 131072, '18')
, ( 'DaysOfMonth', 262144, '19')
, ( 'DaysOfMonth', 524288, '20')
, ( 'DaysOfMonth', 1048576, '21')
, ( 'DaysOfMonth', 2097152, '22')
, ( 'DaysOfMonth', 4194304, '23')
, ( 'DaysOfMonth', 8388608, '24')
, ( 'DaysOfMonth', 16777216, '25')
, ( 'DaysOfMonth', 33554432, '26')
, ( 'DaysOfMonth', 67108864, '27')
, ( 'DaysOfMonth', 134217728, '28')
, ( 'DaysOfMonth', 268435456, '29')
, ( 'DaysOfMonth', 536870912, '30')
, ( 'DaysOfMonth', 1073741824, '31')
, ( 'DaysOfMonth', 8193, '1st and 14th')
, ( 'DaysOfWeek', 1, 'Sun')
, ( 'DaysOfWeek', 2, 'Mon')
, ( 'DaysOfWeek', 4, 'Tues')
, ( 'DaysOfWeek', 8, 'Wed')
, ( 'DaysOfWeek', 16, 'Thurs')
, ( 'DaysOfWeek', 32, 'Fri')
, ( 'DaysOfWeek', 64, 'Sat')
, ( 'DaysOfWeek', 62, 'Mon - Fri')
, ( 'DaysOfWeek', 10, 'Mon - Wed')
, ( 'DaysOfWeek', 24, 'Wed - Thurs')
, ( 'DaysOfWeek', 120, 'Wed - Sat')
, ( 'DaysOfWeek', 126, 'Mon - Sat')
, ( 'DaysOfWeek', 127, 'Daily')
, ( 'DayOfWeek', 1, 'Sun')
, ( 'DayOfWeek', 127, 'Sun')
, ( 'DayOfWeek', 2, 'Mon')
, ( 'DayOfWeek', 10, 'Mon')
, ( 'DayOfWeek', 62, 'Mon')
, ( 'DayOfWeek', 126, 'Mon')
, ( 'DayOfWeek', 127, 'Mon')
, ( 'DayOfWeek', 4, 'Tue')
, ( 'DayOfWeek', 10, 'Tue')
, ( 'DayOfWeek', 62, 'Tue')
, ( 'DayOfWeek', 126, 'Tue')
, ( 'DayOfWeek', 127, 'Tue')
, ( 'DayOfWeek', 8, 'Wed')
, ( 'DayOfWeek', 10, 'Wed')
, ( 'DayOfWeek', 24, 'Wed')
, ( 'DayOfWeek', 62, 'Wed')
, ( 'DayOfWeek', 120, 'Wed')
, ( 'DayOfWeek', 126, 'Wed')
, ( 'DayOfWeek', 127, 'Wed')
, ( 'DayOfWeek', 16, 'Thr')
, ( 'DayOfWeek', 24, 'Thr')
, ( 'DayOfWeek', 62, 'Thr')
, ( 'DayOfWeek', 120, 'Thr')
, ( 'DayOfWeek', 126, 'Thr')
, ( 'DayOfWeek', 127, 'Thr')
, ( 'DayOfWeek', 32, 'Fri')
, ( 'DayOfWeek', 62, 'Fri')
, ( 'DayOfWeek', 120, 'Fri')
, ( 'DayOfWeek', 126, 'Fri')
, ( 'DayOfWeek', 127, 'Fri')
, ( 'DayOfWeek', 64, 'Sat')
, ( 'DayOfWeek', 120, 'Sat')
, ( 'DayOfWeek', 126, 'Sat')
, ( 'DayOfWeek', 127, 'Sat')
) tbl ([GroupName], [CodeNbr], [Label])
)
,
subscription_schedule
AS
(
SELECT
[ScheduleID]
, [SchDaySun] = Sun
, [SchDayMon] = Mon
, [SchDayTue] = Tue
, [SchDayWed] = Wed
, [SchDayThr] = Thr
, [SchDayFri] = Fri
, [SchDaySat] = Sat
, [ScheduleName]
, [ScheduleStartDate]
, [ScheduleEndDate]
, [Flags]
, [RecurrenceType]
, [State]
, [MinutesInterval]
, [DaysInterval]
, [WeeksInterval]
, [DaysOfWeek]
, [DaysOfMonth]
, [Month]
, [MonthlyWeek]
, [ScheduleDays]
FROM
(
SELECT
sc.[ScheduleID]
, sd.[CodeNbr]
, sd.[Label]
, [ScheduleName] = sc.[name]
, [ScheduleStartDate] = sc.[StartDate]
, [ScheduleEndDate] = sc.[EndDate]
, sc.[Flags]
, sc.[RecurrenceType]
, sc.[State]
, sc.[MinutesInterval]
, sc.[DaysInterval]
, sc.[WeeksInterval]
, sc.[DaysOfWeek]
, sc.[DaysOfMonth]
, sc.[Month]
, sc.[MonthlyWeek]
, [ScheduleDays] =
CASE
WHEN sc.[DaysOfMonth] IS NOT NULL THEN COALESCE(dom.[Label], '(' + CAST(sc.[DaysOfMonth] AS VARCHAR(20)) + ') NOT CODED')
WHEN sc.[DaysOfWeek] IS NOT NULL THEN COALESCE(dow.[Label], '(' + CAST(sc.[DaysOfWeek] AS VARCHAR(20)) + ') NOT CODED')
END
--, sc.[RecurrenceType]
FROM
dbo.[Schedule] sc
LEFT JOIN subscription_days sd ON sc.[DaysOfWeek] = sd.[CodeNbr] AND sd.[GroupName] = 'DayOfWeek'
LEFT JOIN subscription_days AS dom ON sc.[DaysOfMonth] = dom.[CodeNbr] AND dom.[GroupName] = 'DaysOfMonth'
LEFT JOIN subscription_days AS dow ON sc.DaysOfWeek = dow.CodeNbr AND dow.[GroupName] = 'DaysOfWeek'
) sch
PIVOT
(
COUNT(sch.[Label])
FOR sch.[Label]
IN ([Sun], [Mon], [Tue], [Wed], [Thr], [Fri], [Sat])
) AS pvt
)
,
report_subscription
AS
(
SELECT
s.[SubscriptionID]
, s.[Report_OID]
, [SubscriptionDescription] = s.[Description]
, s.[ExtensionSettings]
, s.[EventType]
, s.[OwnerID]
, s.[ModifiedByID]
, s.[ModifiedDate]
, [RunTime] = CONVERT(VARCHAR(5), s.[LastRunTime], 8)
, [LastRunDate] = CONVERT(VARCHAR(11),s.[LastRunTime],13)
, s.[LastRunTime]
, s.[DeliveryExtension]
, s.[MatchData]
, [SubscriptionLastStatus] = s.[LastStatus]
, [StatusFail] = CASE WHEN s.[LastStatus] LIKE '%Mail sent%' THEN 'N' ELSE 'Y' END
, [EmailSubject] = CASE CHARINDEX('<Name>SUBJECT</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>SUBJECT</Name><Value>') + CHARINDEX('<Name>SUBJECT</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>SUBJECT</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>SUBJECT</Name><Value>') + CHARINDEX('<Name>SUBJECT</Name><Value>', s.ExtensionSettings))) END
, [EmailTo] = SUBSTRING(s.ExtensionSettings, LEN('<Name>TO</Name><Value>') + CHARINDEX('<Name>TO</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>TO</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>TO</Name><Value>') + CHARINDEX('<Name>TO</Name><Value>', s.ExtensionSettings)))
, [EmailCc] = CASE CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>CC</Name><Value>') + CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>CC</Name><Value>') + CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings))) END
, [EmailBcc] = CASE CHARINDEX('<Name>BCC</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>BCC</Name><Value>') + CHARINDEX('<Name>BCC</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>BCC</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>BCC</Name><Value>') + CHARINDEX('<Name>BCC</Name><Value>', s.ExtensionSettings))) END
, [EmailComment] = CASE CHARINDEX('<Name>Comment</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>Comment</Name><Value>') + CHARINDEX('<Name>Comment</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>Comment</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>Comment</Name><Value>') + CHARINDEX('<Name>Comment</Name><Value>', s.ExtensionSettings))) END
, [EmailIncludeLink] = CASE CHARINDEX('<Name>IncludeLink</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>IncludeLink</Name><Value>') + CHARINDEX('<Name>IncludeLink</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>IncludeLink</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>IncludeLink</Name><Value>') + CHARINDEX('<Name>IncludeLink</Name><Value>', s.ExtensionSettings))) END
, [EmailRenderFormat] = CASE CHARINDEX('<Name>RenderFormat</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>RenderFormat</Name><Value>') + CHARINDEX('<Name>RenderFormat</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>RenderFormat</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>RenderFormat</Name><Value>') + CHARINDEX('<Name>RenderFormat</Name><Value>', s.ExtensionSettings))) END
, [EmailPriority] = CASE CHARINDEX('<Name>Priority</Name><Value>', s.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>Priority</Name><Value>') + CHARINDEX('<Name>Priority</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>Priority</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>Priority</Name><Value>') + CHARINDEX('<Name>Priority</Name><Value>', s.ExtensionSettings))) END
, sch.[MinutesInterval]
, sch.[DaysInterval]
, sch.[WeeksInterval]
, sch.[DaysOfWeek]
, sch.[DaysOfMonth]
, sch.[Month]
, sch.[MonthlyWeek]
--, [JobName] = sj.[name]
, sch.[ScheduleName]
, sch.[ScheduleDays]
, sch.[SchDaySun]
, sch.[SchDayMon]
, sch.[SchDayTue]
, sch.[SchDayWed]
, sch.[SchDayThr]
, sch.[SchDayFri]
, sch.[SchDaySat]
, sch.[ScheduleStartDate]
, sch.[ScheduleEndDate]
, sch.[Flags]
, sch.[RecurrenceType]
, sch.[State]
FROM
dbo.[Subscriptions] AS s
LEFT JOIN dbo.[Notifications] AS n ON n.[SubscriptionID] = s.[SubscriptionID] AND s.[Report_OID] = n.[ReportID]
LEFT JOIN dbo.[ReportSchedule] AS rs ON s.[SubscriptionID] = rs.[SubscriptionID]
--LEFT JOIN MSDB.dbo.[sysjobs] AS sj ON sj.[name] = CAST(rs.[ScheduleID] AS VARCHAR(255))
LEFT JOIN subscription_schedule AS sch ON rs.[ScheduleID] = sch.[ScheduleID]
WHERE
1=1
--AND sch.[RecurrenceType] IN(4,5) -- 1 = is one off, 4 = daily, 5 = monthly
--AND s.EventType = 'TimedSubscription'
)
SELECT
c.[Name]
, c.[Description]
, c.[Parameter]
, c.[ReportFolder]
, c.[ReportPath]
, [URL_ReportFolder] = c.[UrlPath] + c.[ReportFolder] + '&ViewMode=List'
, [URL_Report] = c.[UrlPath] + c.[ReportFolder] + '%2f' + c.Name
, [URL] = 'http://' + Host_Name() + '/Reports/Pages/SubscriptionProperties.aspx?ItemPath=' + c.ReportPath + '&IsDataDriven=False&SubscriptionID=' + CAST(s.SubscriptionID AS VARCHAR(80))
, [URL2] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=' + c.[ReportPath] + '&SelectedTabId=SubscriptionsTab'
, [ReportCreatedBy] = urc.[SimpleUserName]
, c.[ReportCreationDate]
, [ReportModifiedBy] = urm.[SimpleUserName]
, c.[ReportModifiedDate]
, [SubscriptionOwner] = usc.[SimpleUserName]
, [SubscriptionModifiedBy] = usm.[SimpleUserName]
, [SubscriptionModifiedDate] = s.[ModifiedDate]
, s.[SubscriptionID]
, s.[SubscriptionDescription]
, s.[ExtensionSettings]
, s.[EventType]
, s.[EmailSubject]
, s.[EmailTo]
, s.[EmailCc]
, s.[EmailBcc]
, s.[EmailComment]
, s.[EmailIncludeLink]
, s.[EmailRenderFormat]
, s.[EmailPriority]
, s.[DeliveryExtension]
, s.[SubscriptionLastStatus]
, s.[StatusFail]
, s.[MatchData]
, s.[RunTime]
, s.[LastRunDate]
, s.[LastRunTime]
, s.[MinutesInterval]
, s.[DaysInterval]
, s.[WeeksInterval]
, s.[DaysOfWeek]
, s.[DaysOfMonth]
, s.[Month]
, s.[MonthlyWeek]
, [JobName] = NULL --, s.[JobName]
, s.[ScheduleName]
, s.[ScheduleDays]
, s.[SchDaySun]
, s.[SchDayMon]
, s.[SchDayTue]
, s.[SchDayWed]
, s.[SchDayThr]
, s.[SchDayFri]
, s.[SchDaySat]
, s.[ScheduleStartDate]
, s.[ScheduleEndDate]
, s.[Flags]
, s.[RecurrenceType]
, s.[State]
, [EventStatus] = el.[Status]
, [EventDateTime] = el.[TimeEnd]
FROM
report_catalog AS c
INNER JOIN report_subscription AS s ON s.[Report_OID] = c.[ItemID]
LEFT OUTER JOIN (SELECT b.[ReportID], b.[Status], b.[TimeEnd]
FROM dbo.[ExecutionLog] b
INNER JOIN (SELECT [ReportID], MAX([TimeEnd]) AS [TimeEnd]
FROM dbo.[ExecutionLog]
GROUP BY [ReportID]) a ON b.[ReportID] = a.[ReportID] AND b.[TimeEnd] = a.[TimeEnd]
)AS el ON el.[ReportID] = c.[ItemID]
LEFT OUTER JOIN report_users AS urc ON c.[CreatedById] = urc.[UserID]
LEFT OUTER JOIN report_users AS urm ON c.[ModifiedById] = urm.[UserID]
LEFT OUTER JOIN report_users AS usc ON s.[OwnerID] = usc.[UserID]
LEFT OUTER JOIN report_users AS usm ON s.[ModifiedByID] = usm.[UserID]
WHERE
1=1
AND c.[Type] = 2
AND (#all_value IN (#ReportFolder) OR c.[ReportFolder] IN(#ReportFolder))
AND (#all_value IN (#ReportFolder) OR CHARINDEX(#ReportFolder, c.[ReportPath]) > 0)
AND (#all_value IN(#ReportName) OR c.[Name] IN(#ReportName))
AND (#all_value IN(#EventStatus) OR el.[Status] IN(#EventStatus))
AND (#all_value IN(#Current) OR CASE WHEN s.[ScheduleEndDate] IS NULL THEN 'Current' WHEN s.[ScheduleEndDate] IS NOT NULL THEN 'Non Current' END = #Current)
AND (#all_value IN(#SubscriptionStatus) OR s.[SubscriptionLastStatus] LIKE '%' + #SubscriptionStatus + '%')
AND (s.[LastRunTime] >= #LastSubscriptionDate OR #LastSubscriptionDate IS NULL)
AND
(
(SUBSTRING(s.[ExtensionSettings], LEN('<Name>TO</Name><Value>') + CHARINDEX('<Name>TO</Name><Value>', s.[ExtensionSettings]), CHARINDEX('</Value>', s.[ExtensionSettings], CHARINDEX('<Name>TO</Name><Value>', s.[ExtensionSettings]) + 1) - (LEN('<Name>TO</Name><Value>') + CHARINDEX('<Name>TO</Name><Value>', s.[ExtensionSettings])))
LIKE '%' + #EmailLike + '%' OR #EmailLike IS NULL
)
OR
(
CASE CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings)
WHEN 0 THEN ''
ELSE SUBSTRING(s.ExtensionSettings, LEN('<Name>CC</Name><Value>') + CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.ExtensionSettings, CHARINDEX('<Name>CC</Name><Value>', s.ExtensionSettings) + 1) - (LEN('<Name>CC</Name><Value>') + CHARINDEX('<Name>CC</Name><Value>', s.[ExtensionSettings])))
END
LIKE '%' + #EmailLike + '%'
)
OR
(
CASE CHARINDEX('<Name>BCC</Name><Value>', s.[ExtensionSettings])
WHEN 0 THEN ''
ELSE SUBSTRING(s.[ExtensionSettings], LEN('<Name>BCC</Name><Value>') + CHARINDEX('<Name>BCC</Name><Value>', s.ExtensionSettings), CHARINDEX('</Value>', s.[ExtensionSettings], CHARINDEX('<Name>BCC</Name><Value>', s.[ExtensionSettings]) + 1) - (LEN('<Name>BCC</Name><Value>') + CHARINDEX('<Name>BCC</Name><Value>', s.[ExtensionSettings])))
END
LIKE '%' + #EmailLike + '%')
)
To answer your third question, I would use roles in the report folders to manage permissions.
In SSRS, new roles and adjustments to existing roles must be performed in SQL Server Management studio, SSMS. After opening up SSMS, click on "Connect" and select "Reporting Services…"
Enter your Server Name and login information and then click Connect.
After connecting to the Report Server, open the Security Folder right click on "Roles" and click on "New Role…"
You can create a new role Subscription Editor or Functional Owner and then you can assign permissions to the new roles based on what you want the user(s) to be able to do.
Then on the report manager click on the down arrow for a folder and select "Security"
Then click "New Role Assignment"
Then enter the Active Directory group or an email address and check the new role you created.
Here is a more detailed wiki I wrote for report server permission on MSDN.

mysql sum top 5 scores per player and put in ranking

I want to make a ranking with the best 5 scores of the players summed and put in a ranking. Players have more or less then 5 scores.
For now I have the following query:
set #count:=0, #player:='';
SELECT SEIZOEN
, WEDSTRIJDTYPE
, ATLEET_ID
, GROEP_NAAM
, GROEP_OMS
, SUM(PUNTEN_WC) as WC_RESULT
FROM
( SELECT ATLEET_ID
, PUNTEN_WC
, SEIZOEN
, WEDSTRIJDTYPE
, GROEP_NAAM
, GROEP_OMS
FROM
( SELECT PUNTEN_WC
, SEIZOEN
, WEDSTRIJDTYPE
, GROEP_NAAM
, GROEP_OMS
, #count := if (#player != ATLEET_ID,0,#count + 1) as count
, #player := ATLEET_ID as ATLEET_ID
FROM
( SELECT ATLEET_ID
, PUNTEN_WC
, k.SEIZOEN
, k.WEDSTRIJDTYPE
, g.GROEP_NAAM
, g.GROEP_OMS
FROM RESULTATEN r
LEFT
JOIN KALENDER k
ON r.KALENDER_ID = k.KALENDER_ID
JOIN GROEP_SNB g
ON r.GROEP_NAAM = g.GROEP_NAAM
JOIN SKIER s
ON r.ATLEET_ID = s.SKIER_ID
WHERE k.WEDSTRIJDTYPE = 'Dutch Cup snowboard '
AND k.SEIZOEN = '2016-2017'
order
by ATLEET_ID
, PUNTEN_WC DESC
) x
) y
where count < 6
) z
GROUP
BY ATLEET_ID
ORDER
BY GROEP_NAAM
, WC_RESULT DESC
LIMIT 0,2000;
The problem is this query doesn't take the five best scores of each player.
When I run the most inner query it's sorts the scores fine.
SELECT ATLEET_ID
, PUNTEN_WC
, k.SEIZOEN
, k.WEDSTRIJDTYPE
, g.GROEP_NAAM
, g.GROEP_OMS
FROM RESULTATEN r
LEFT
JOIN KALENDER k
ON r.KALENDER_ID = k.KALENDER_ID
JOIN GROEP_SNB g
ON r.GROEP_NAAM = g.GROEP_NAAM
JOIN SKIER s
ON r.ATLEET_ID = s.SKIER_ID
WHERE k.WEDSTRIJDTYPE = 'Dutch Cup snowboard '
AND k.SEIZOEN = '2016-2017'
order
by ATLEET_ID
, PUNTEN_WC DESC
I've put a count on the records so I can limit it to best of 5. But then the trouble starts. With the second query the highscores are still ordered correctly but the count-field is not 0 to 5?
So when I put the third query in it stops when count-field is 5, but I want a maximum of 5 scores per player.
You can sum the top N values for each person with this query:
Creating a simple test table and populating it -
CREATE TABLE Scores
(`id` int, `playerName` varchar(16), `score` int)
;
INSERT INTO Scores
(`id`, `playerName`, `score`)
VALUES
(1, 'Joe', 5),
(2, 'Joe', 5),
(3, 'Joe', 5),
(4, 'Joe', 1),
(5, 'Joe', 10),
(6, 'Joe', 10),
(7, 'Joe', 15),
(8, 'Bob', 5),
(9, 'Bob', 5),
(10, 'Bob', 2),
(11, 'Bob', 10),
(12, 'Bob', 3),
(13, 'Bob', 10),
(14, 'Bob', 20)
;
The query:
SET #score_rank := 0;
SET #current_player = '';
SET #topN = 5;
Select playerName, SUM(score)
From (Select playerName, score,
#score_rank := IF(#current_player = playerName, (#score_rank + 1), 1) AS score_rank,
#current_player := playerName
From Scores
Order By playerName, score DESC) sorted
Where score_rank <= #topN
Group By playerName;
The inner query assigns values to two variables - #current_player and #score_rank. If the #current_player value matches playerName, it increments #score_rank, otherwise it sets the #score_rank to 1. By doing this, we can grab only the top 5 for each player. The outer query then sums those top 5 scores. You can change the value of #topN if you want to sum a different set (like top 10).
Results with the above sample table:
playerName SUM(score)
---------- ----------
Bob 50
Joe 45
See it here: http://rextester.com/CLO11640

Update multiple columns with GROUP_CONCAT not working as expected

Help wanted fellas! I have a stored precedure that updates the columns of a calendar-style table from another one. The records of the second one should be stored in the calendar grouped according its date and individual, however I cannot achieve it in a single UPDATE sentence; I had to make these ugly series of column-by-column updates. If you have any idea, it will be appreciated. Code is below:
DECLARE thisYearMonth VARCHAR(7);
SET thisYearMonth = '2016-09';
UPDATE calendar CAL
INNER JOIN (
SELECT checkinout.userid,
checkinout.checktime,
GROUP_CONCAT(checkinout.checktime) ORDER BY checkinout.id SEPARATOR ' | ') AS checktime
FROM checkinout
INNER JOIN calendar ON calendar.userid = checkinout.userid
WHERE checkinout.userid = calendar.userid
AND DATE(checktime) = CONCAT(thisYearMonth, '-', '01')
GROUP BY userid
) CHK ON CHK.userid = CAL.userid
SET CAL.day1 = CHK.checkstatus;
UPDATE calendar CAL
INNER JOIN (
SELECT checkinout.userid,
checkinout.checktime,
GROUP_CONCAT(checkinout.checktime ORDER BY checkinout.id SEPARATOR ' | ') AS checktime
FROM checkinout
INNER JOIN calendar ON calendar.userid = checkinout.userid
WHERE checkinout.userid = calendar.userid
AND DATE(checktime) = CONCAT(thisYearMonth, '-', '02')
GROUP BY userid
) CHK ON CHK.userid = CAL.userid
SET CAL.day2 = CHK.checkstatus;
And so on until day n. The question is how do I make it work like just a single UPDATE that does not repeats in all remaning calendar rows the same value as the row "day1", i.e. day1 gets 10:00, day2 gets 10:00 and so on. Here's the code that generates this behavior:
UPDATE calendar CAL
INNER JOIN (
SELECT checkinout.userid,
checkinout.checktime,
GROUP_CONCAT(checkinout.checktime) ORDER BY checkinout.id SEPARATOR ' | ') AS checktime
FROM checkinout
INNER JOIN calendar ON calendar.userid = checkinout.userid
WHERE checkinout.userid = calendar.userid
AND DATE(checktime) = CONCAT(thisYearMonth, '-', '01')
GROUP BY userid
) CHK ON CHK.userid = CAL.userid
SET CAL.day1 = CHK.checkstatus,
CAL.day2 = CHK.checkstatus,
CAL.day3 = CHK.checkstatus
...;
EDIT: According to Gordon Linoff this can be achieved using conditional aggregation, however it only brings one record per row and not all of the records that correspond to every userid on each day.
Like this:
Results using conditional aggregation
Expected result:
Result updating row by row individually
I'm posting this sample data in the code below for you to verify my results
DROP TABLE IF EXISTS tmp_checkinout;
CREATE TEMPORARY TABLE tmp_checkinout
(`id` int, `userid` int, `checktime` datetime, `checkstatus` varchar(8));
INSERT INTO tmp_checkinout
(`id`, `userid`, `checktime`, `checkstatus`)
VALUES
(1 , 3, '2016-8-1 07:49:23', 'SHRP'),
(2 , 2, '2016-8-1 08:01:40', 'SHRP'),
(3 , 1, '2016-8-1 08:49:07', 'SHRP'),
(4 , 5, '2016-8-1 09:14:19', 'LATE'),
(5 , 3, '2016-8-2 07:48:06', 'SHRP'),
(6 , 2, '2016-8-2 08:04:03', 'SHRP'),
(7 , 4, '2016-8-2 08:04:12', 'SHRP'),
(8 , 1, '2016-8-2 08:49:07', 'SHRP'),
(9 , 5, '2016-8-2 09:10:31', 'TOLR'),
(10, 3, '2016-8-2 10:40:16', 'EXTN'),
(11, 3, '2016-8-3 07:48:32', 'SHRP'),
(12, 2, '2016-8-3 08:05:34', 'SHRP'),
(13, 4, '2016-8-3 08:12:23', 'LATE'),
(14, 5, '2016-8-3 09:08:52', 'TOLR'),
(15, 1, '2016-8-3 10:23:41', 'EXTN'),
(16, 3, '2016-8-4 07:49:15', 'SHRP'),
(17, 2, '2016-8-4 08:05:39', 'SHRP'),
(18, 1, '2016-8-4 08:36:44', 'SHRP'),
(19, 4, '2016-8-4 08:07:22', 'TOLR'),
(20, 5, '2016-8-4 09:22:34', 'LATE'),
(21, 3, '2016-8-5 07:51:42', 'SHRP'),
(22, 4, '2016-8-5 08:11:33', 'LATE'),
(23, 2, '2016-8-5 08:16:54', 'LATE'),
(24, 1, '2016-8-5 08:53:20', 'SHRP'),
(25, 5, '2016-8-5 09:26:02', 'LATE'),
(26, 3, '2016-8-2 10:52:44', 'EXTN')
;
DROP TABLE IF EXISTS tmp_calendar;
CREATE TEMPORARY TABLE tmp_calendar
(`userid` int, `day1` varchar(40), `day2` varchar(40), `day3` varchar(40), `day4` varchar(40), `day5` varchar(40));
INSERT INTO tmp_calendar
(`userid`)
VALUES (1), (2), (3), (4), (5);
Using Gordon Linoff's answer, this is the code that generates the results as described in picture 1:
UPDATE tmp_calendar AS cal
INNER JOIN
(SELECT id, userid,
CASE WHEN DAY(checktime) = 1 THEN CONCAT('ID:', id, ', ', checkstatus, ', ', checktime) ELSE NULL END AS timeandstatus_01,
CASE WHEN DAY(checktime) = 2 THEN CONCAT('ID:', id, ', ', checkstatus, ', ', checktime) ELSE NULL END AS timeandstatus_02,
CASE WHEN DAY(checktime) = 3 THEN CONCAT('ID:', id, ', ', checkstatus, ', ', checktime) ELSE NULL END AS timeandstatus_03,
CASE WHEN DAY(checktime) = 4 THEN CONCAT('ID:', id, ', ', checkstatus, ', ', checktime) ELSE NULL END AS timeandstatus_04,
CASE WHEN DAY(checktime) = 5 THEN CONCAT('ID:', id, ', ', checkstatus, ', ', checktime) ELSE NULL END AS timeandstatus_05
FROM tmp_checkinout
WHERE DATE_FORMAT(checktime, '%Y-%m') = '2016-08'
ORDER BY id ASC) AS chk ON chk.userid = cal.userid
SET cal.day1 = chk.timeandstatus_01,
cal.day2 = chk.timeandstatus_02,
cal.day3 = chk.timeandstatus_03,
cal.day4 = chk.timeandstatus_04,
cal.day5 = chk.timeandstatus_05
WHERE cal.userid = chk.userid;
Thanks for any pointer :-)
I think you need conditional aggregation in the subquery:
UPDATE calendar CAL INNER JOIN
(SELECT ch.userid, ch.checktime,
GROUP_CONCAT(CASE WHEN DAY(checktime) = 01 THEN ch.checktime END ORDER BY ch.id SEPARATOR ' | ') AS checktime_01,
GROUP_CONCAT(CASE WHEN DAY(checktime) = 02 THEN ch.checktime END ORDER BY ch.id SEPARATOR ' | ') AS checktime_02,
. . .
FROM checkinout ch INNER JOIN
calendar ca
ON ca.userid = ch.userid
WHERE date_format(checktime, '%Y-%m') = thisYearMonth
GROUP BY userid
) CHK
ON CHK.userid = CAL.userid
SET CAL.day1 = CHK.checkstatus_01,
CAL.day2 = CHK.checkstatus_02;