I have a view in SQL that when I want to open it gives me the following message: #1242 - Subquery returns more than 1 line.
How can I correct this query considering my sql script?
My code is:
SELECT
`sc`.`id` AS `id`,
`sc`.`id_agente_solicitado` AS `id_agente_solicitado`,
`sc`.`id_agente_solicitante` AS `id_agente_solicitante`,
`sc`.`fecha_solicitada` AS `fecha`,
`sc`.`horario_solicitado` AS `hora`,
`sc`.`pendiente` AS `pendiente`,
'1' AS `tipo`,
'Cambios de horarios' AS `grupo`,
'1' AS `grupo_numero`,
CONCAT(`a`.`nombres`, ' ', `a`.`apellidos`) AS `agente_solicitado_nombre`,
(
SELECT
CONCAT(
`sigsiste_bd`.`agentes`.`nombres`,
' ',
`sigsiste_bd`.`agentes`.`apellidos`
)
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `agente_solicitante_nombre`,
(
SELECT
`sigsiste_bd`.`agentes`.`imagen_perfil`
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `imagen_perfil_solicitante`,
`a`.`imagen_perfil` AS `imagen_perfil_solicitado`,
DAYNAME(`sc`.`fecha_solicitada`) AS `nombre_dia`,
CONCAT(
CONVERT(
DATE_FORMAT(`sc`.`fecha_solicitada`, '%d') USING utf8mb4
),
' de ',
CONVERT(
MONTHNAME(`sc`.`fecha_solicitada`) USING utf8mb4
),
' de ',
CONVERT(
DATE_FORMAT(`sc`.`fecha_solicitada`, '%Y') USING utf8mb4
)
) AS `nombre_mes`,
(
SELECT
CONCAT(' ', `det`.`ingreso`)
FROM
(
`sigsiste_bd`.`planilla_horarios_det` `det`
LEFT JOIN `sigsiste_bd`.`planilla_horarios_cab` `cab`
ON
(
(
`cab`.`id_planilla_horarios_cab` = `det`.`id_planilla_horarios_cab`
)
)
)
WHERE
(
(
STR_TO_DATE(
CONCAT(
`cab`.`ano_correspondiente`,
',',
`cab`.`mes_correspondiente`,
',',
`det`.`dia`
),
'%Y,%m,%d'
) = `sc`.`fecha_solicitada`
) AND(
`sc`.`id_agente_solicitante` = `det`.`id_agente`
)
)
) AS `cambio_por`
FROM
(
`sigsiste_bd`.`solicitudes_cambio_horario` `sc`
LEFT JOIN `sigsiste_bd`.`agentes` `a`
ON
(
(
`a`.`id_agente` = `sc`.`id_agente_solicitado`
)
)
)
UNION ALL
SELECT
`sc`.`id` AS `id`,
`sc`.`id_agente_solicitado` AS `id_agente_solicitado`,
`sc`.`id_agente_solicitante` AS `id_agente_solicitante`,
`sc`.`fecha_cobertura` AS `fecha`,
`sc`.`horario_cobertura` AS `hora`,
`sc`.`pendiente` AS `pendiente`,
'2' AS `tipo`,
'Coberturas' AS `grupo`,
'2' AS `grupo_numero`,
CONCAT(`a`.`nombres`, ' ', `a`.`apellidos`) AS `agente_solicitado_nombre`,
(
SELECT
CONCAT(
`sigsiste_bd`.`agentes`.`nombres`,
' ',
`sigsiste_bd`.`agentes`.`apellidos`
)
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `agente_solicitante_nombre`,
(
SELECT
`sigsiste_bd`.`agentes`.`imagen_perfil`
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `imagen_perfil_solicitante`,
`a`.`imagen_perfil` AS `imagen_perfil_solicitado`,
DAYNAME(`sc`.`fecha_cobertura`) AS `nombre_dia`,
CONCAT(
CONVERT(
DATE_FORMAT(`sc`.`fecha_cobertura`, '%d') USING utf8mb4
),
' de ',
CONVERT(
MONTHNAME(`sc`.`fecha_cobertura`) USING utf8mb4
),
' de ',
CONVERT(
DATE_FORMAT(`sc`.`fecha_cobertura`, '%Y') USING utf8mb4
)
) AS `nombre_mes`,
'' AS `cambio_por`
FROM
(
`sigsiste_bd`.`solicitudes_cobertura` `sc`
LEFT JOIN `sigsiste_bd`.`agentes` `a`
ON
(
(
`a`.`id_agente` = `sc`.`id_agente_solicitado`
)
)
)
UNION ALL
SELECT
`sc`.`id` AS `id`,
`sc`.`id_agente_solicitado` AS `id_agente_solicitado`,
`sc`.`id_agente_solicitante` AS `id_agente_solicitante`,
`sc`.`fecha_devolucion` AS `fecha`,
`sc`.`horario_devolucion` AS `hora`,
`sc`.`pendiente` AS `pendiente`,
'3' AS `tipo`,
'Devoluciones' AS `grupo`,
'3' AS `grupo_numero`,
CONCAT(`a`.`nombres`, ' ', `a`.`apellidos`) AS `agente_solicitado_nombre`,
(
SELECT
CONCAT(
`sigsiste_bd`.`agentes`.`nombres`,
' ',
`sigsiste_bd`.`agentes`.`apellidos`
)
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `agente_solicitante_nombre`,
(
SELECT
`sigsiste_bd`.`agentes`.`imagen_perfil`
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `imagen_perfil_solicitante`,
`a`.`imagen_perfil` AS `imagen_perfil_solicitado`,
DAYNAME(`sc`.`fecha_devolucion`) AS `nombre_dia`,
CONCAT(
CONVERT(
DATE_FORMAT(`sc`.`fecha_devolucion`, '%d') USING utf8mb4
),
' de ',
CONVERT(
MONTHNAME(`sc`.`fecha_devolucion`) USING utf8mb4
),
' de ',
CONVERT(
DATE_FORMAT(`sc`.`fecha_devolucion`, '%Y') USING utf8mb4
)
) AS `nombre_mes`,
'' AS `cambio_por`
FROM
(
`sigsiste_bd`.`solicitudes_devoluciones` `sc`
LEFT JOIN `sigsiste_bd`.`agentes` `a`
ON
(
(
`a`.`id_agente` = `sc`.`id_agente_solicitado`
)
)
)
I have a view in SQL that after trying to open it gives me the following message: #1242 - Subquery returns more than 1 line.
How can I correct my query?
It is not possible to be sure, as you have not included nearly enough detail, but I suspect the error is being caused by the subquery for cambio_por as the other subqueries appear to be based on the PK -
(
SELECT
CONCAT(' ', `det`.`ingreso`)
FROM
(
`sigsiste_bd`.`planilla_horarios_det` `det`
LEFT JOIN `sigsiste_bd`.`planilla_horarios_cab` `cab`
ON
(
(
`cab`.`id_planilla_horarios_cab` = `det`.`id_planilla_horarios_cab`
)
)
)
WHERE
(
(
STR_TO_DATE(
CONCAT(
`cab`.`ano_correspondiente`,
',',
`cab`.`mes_correspondiente`,
',',
`det`.`dia`
),
'%Y,%m,%d'
) = `sc`.`fecha_solicitada`
) AND(
`sc`.`id_agente_solicitante` = `det`.`id_agente`
)
)
) AS `cambio_por`
to test you could try replacing it with an empty string, as you have for the other two selects -
'' AS `cambio_por`
Each of the three outer selects has two subqueries in the select list to retrieve values from sigsiste_bd.agentes based on sc.id_agente_solicitante. These should probably be replaced by another join.
...
(
SELECT
CONCAT(
`sigsiste_bd`.`agentes`.`nombres`,
' ',
`sigsiste_bd`.`agentes`.`apellidos`
)
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `agente_solicitante_nombre`,
(
SELECT
`sigsiste_bd`.`agentes`.`imagen_perfil`
FROM
`sigsiste_bd`.`agentes`
WHERE
(
`sigsiste_bd`.`agentes`.`id_agente` = `sc`.`id_agente_solicitante`
)
) AS `imagen_perfil_solicitante`,
...
FROM
(
`sigsiste_bd`.`solicitudes_cambio_horario` `sc`
LEFT JOIN `sigsiste_bd`.`agentes` `a`
ON
(
(
`a`.`id_agente` = `sc`.`id_agente_solicitado`
)
)
)
would become
...
CONCAT(`agente_solicitante`.`nombres`, ' ', `agente_solicitante`.`apellidos`) AS `agente_solicitante_nombre`,
`agente_solicitante`.`imagen_perfil` AS `imagen_perfil_solicitante`,
...
FROM `sigsiste_bd`.`solicitudes_cambio_horario` `sc`
LEFT JOIN `sigsiste_bd`.`agentes` `a`
ON `a`.`id_agente` = `sc`.`id_agente_solicitado`
LEFT JOIN `sigsiste_bd`.`agentes` `agente_solicitante`
ON `agente_solicitante`.`id_agente` = `sc`.`id_agente_solicitante`
Your expression for nombre_mes can be simplified -
/* From */
CONCAT(
CONVERT(
DATE_FORMAT(`sc`.`fecha_cobertura`, '%d') USING utf8mb4
),
' de ',
CONVERT(
MONTHNAME(`sc`.`fecha_cobertura`) USING utf8mb4
),
' de ',
CONVERT(
DATE_FORMAT(`sc`.`fecha_cobertura`, '%Y') USING utf8mb4
)
) AS `nombre_mes`,
/* To */
CONVERT(DATE_FORMAT(`sc`.`fecha_solicitada`, '%d de %M de %Y') USING utf8mb4) AS `nombre_mes`,
I am getting this following error , the same code is not throwing any error in my local system.
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'GROUP_CONCAT(CASE WHEN atv.alid = 1906962 and atv.atrtid = 1
THEN concat(replac' at line 1
below i posted my code
BEGIN
SET
##group_concat_max_len = 1024 * 13;
SET
#sql3 = NULL;
SELECT
GROUP_CONCAT(
CONCAT(
'replace(format(SUM(CASE WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 THEN concat((atv.amount) , "") when atv.alid =',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount) , "") END),2), ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'`'),
'.',
't'
),
' , replace(format( SUM(case when atv.alid = ',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount/',
b.value,
'*100),"") WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 then concat((atv.amount/',
b.value,
'*100) , "") end),2), ", ","") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'-value`'),
'.',
't'
)
)
)
INTO
#sql1
FROM
business_tax_profile b
LEFT JOIN
account_ledger acl ON(
acl.alid = b.alid AND acl.company_id = 19
)
WHERE
b.butaptid = 2 AND b.butapsid = 1 AND b.company_id = 19;
SELECT
GROUP_CONCAT(
CONCAT(
'replace(format(SUM(CASE WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 THEN concat((atv.amount) , "") when atv.alid =',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount) , "") END) , 2) , ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'`'),
'.',
't'
),
' , replace(format(SUM(case when atv.alid = ',
b.alid,
' and atv.atrtid = 2 then concat((atv.amount/',
b.value,
'*100),"") WHEN atv.alid = ',
b.alid,
' and atv.atrtid = 1 then concat((atv.amount/',
b.value,
'*100) , "") end),2) , ", " , "") as ',
REPLACE
(
CONCAT('`',
TRIM(acl.name),
'-value`'),
'.',
't'
)
)
)
INTO
#sql4
FROM
business_tax_sub_profile b
LEFT JOIN
account_ledger acl ON(
acl.alid = b.alid AND acl.company_id = 19
)
WHERE
b.butasuptid = 2 AND b.company_id = 19 AND b.butasupsid = 1;
SELECT
GROUP_CONCAT(
CONCAT(
'GROUP_CONCAT(CASE WHEN atv.alid = ',
c.alid,
' and atv.atrtid = 1 THEN concat(replace(format(atv.amount,2),", ","") , "") when atv.alid=',
c.alid,
' AND atv.atrtid = 2 then concat(replace(format(atv.amount , 2),", ","") , "") END) as `',
TRIM(ao.name),
'`'
)
)
INTO
#sql2
FROM
extra_charges c
LEFT JOIN
account_ledger ao ON(
ao.alid = c.alid AND ao.company_id = 19
)
WHERE
c.ectid = 2 AND c.company_id = 19 AND c.ecsid = 1;
SET
#sql3 = CONCAT(
'CREATE OR REPLACE ALGORITHM = UNDEFINED DEFINER = root#localhost SQL SECURITY DEFINER VIEW `purchase_invoice_tax_report_view_19` AS SELECT i.pinvid as pinvid, ROUND(i.total_tax_amount,2) AS `total_tax_amount1`, i.outlet_chkid,i.receive_date as receive_date, i.total_qty, replace(format(i.payable_amount,2),", ","") as payable_amount, replace(format((i.complete_amount -i.total_tax_amount),2) , ", " , "") as total_amount_before_tax, v.gstin, v.data as vendor_data, group_concat((case when atv.alid = 35 and atv.atrtid = 1 then concat(replace(format(atv.amount,2),", ","") , "") when atv.alid = 35 and atv.atrtid = 2 then concat(replace(format(atv.amount,2),", ",""), "") end) separator " ") as `round`,',
COALESCE(#sql1,
'"0"'),
',',
COALESCE(#sql4,
'"0"'),
',',
COALESCE(#sql2,
'"0"'),
', al.name as vendor_name , i.date, (CASE WHEN i.is_transportation IS NULL and is_expense = 0 THEN "Purchase" WHEN i.is_transportation IS NULL and is_expense > 0 THEN "Expense" WHEN i.is_transportation > 0 and is_expense >0 THEN "Transportation" ELSE "Purchase" END) as purchase_type,i.invoice_number ,(case when a.avtid = 3 then "Purchases" end) as voucher_type , a.avtid, i.pinvsid FROM purchase_invoice i LEFT JOIN account_transaction atv ON(atv.avid = i.avid and atv.company_id = 19) left join account_voucher a on (a.avid = atv.avid and a.company_id=19) LEFT join vendor v on (v.venid = i.venid and v.company_id = 19) LEFT join account_ledger al on(al.alid = v.alid and al.company_id = 19) where a.avsid = 1 and a.avtid = 3 and a.company_id = 19 group by i.pinvid'
);
PREPARE
stmt
FROM
#sql3;
EXECUTE
stmt;
DEALLOCATE
PREPARE
stmt;
END
is there any syntax error or anything else because the same code working fine in the local system ....
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.
I tried and searched the solution for the below problem statement but unfortunately I didn't get the exact output. I need to display the complete organizational hierarchy in the below format. I tried with using CTE with UNION ALL but still I'm unable to get the exact output.
Table structure:
CREATE TABLE EMPMASTER
(
EMPID CHAR(10),
EMPNAME NVARCHAR(50),
EMPDESIG VARCHAR(20),
MRGID CHAR(10)
);
Output:
EMPNAME EMPID EMP DESIGNATION
------------------------------------
EMP1 00001 CEO
EMP2 00009 MANAGER 1
EMP3 00005 TL1
EMP4 00003 SSD1
EMP5 00006 SD1
EMP6 00008 TL2
EMP7 00020 SSD2
EMP8 25 SD2
EMP9 00030 TL3
EMP10 00017 MANAGER2
EMP11 00029 TL4
EMP12 00045 SSD3
EMP13 00060 SSD4
EMP14 00070 SD3
EMP15 00060 SD4
EMP16 00090 SD5
EMP17 00055 SD6
CONTI… CONTI… CONTI…
Code that I tried:
WITH HierarchyTree (EMPID, EMPNAME, EMPDESIG, MRGID, Rank)
AS
(
-- Anchor member definition
SELECT
EMPID, EMPNAME, EMPDESIG, MRGID, 0 AS Rank
FROM
EMPMASTER AS e
WHERE
DESIGNATION = 'Admin' AND EMPLOYEE_ID='1'
UNION ALL
-- Recursive member definition
SELECT
e.EMPID, e.EMPNAME, e.EMPDESIG, e.MRGID, Rank + 1
FROM
EMPMASTER AS e
INNER JOIN
HierarchyTree AS d ON e.REPORTINGTO = d.EMPLOYEE_ID
)
SELECT
EMPID, EMPNAME, DESIGNATION, REPORTINGTO, Rank
FROM
HierarchyTree
Sample data
EMPID EMPNAME EMPDESIG MRGID
1 RAM CEO 0
7326 MOHD RAFI MANAGER 7454
7454 PMT PHARMA MANAGER 1
2094 VAC SANJAY DEVELOPER 14005
602 GS MANAGER 7454
412 RAJESH LEAD 602
14005 VAC SM N LEAD 7326
34395 DEEPAK LEAD 7326
16430 VIJAY DEVELOPER 34395
I would venture to suggest an answer based on the hierarchy diagram:
declare #EMPMASTER table
(
EMPID CHAR(10) ,
EMPNAME NVARCHAR(50) ,
EMPDESIG VARCHAR(20) ,
MRGID CHAR(10)
);
insert into #EMPMASTER values
( '00001', 'EMP1', 'CEO', null ),
( '00002', 'EMP2', 'MANAGER1', '00001' ),
( '00003', 'EMP3', 'TL1', '00002' ),
( '00004', 'EMP4', 'SSD1', '00003' ),
( '00005', 'EMP5', 'SD1', '00004' ),
( '00006', 'EMP6', 'TL2', '00002' ),
( '00007', 'EMP7', 'SSD2', '00006' ),
( '00008', 'EMP8', 'SD2', '00007' ),
( '00009', 'EMP9', 'TL3', '00002' ),
( '00010', 'EMP10', 'MANAGER2', '00001' ),
( '00011', 'EMP11', 'TL4', '00010' ),
( '00012', 'EMP12', 'SSD3', '00011' ),
( '00013', 'EMP13', 'SSD4', '00011' ),
( '00014', 'EMP14', 'SD3', '00013' ),
( '00015', 'EMP15', 'SD4', '00013' ),
( '00016', 'EMP16', 'SD5', '00013' ),
( '00017', 'EMP17', 'SD6', '00013' ),
( '00018', 'EMP18', 'MANAGER3', '00001' ),
( '00019', 'EMP19', 'TL5', '00018' ),
( '00020', 'EMP20', 'SSD5', '00019' ),
( '00021', 'EMP21', 'SSD6', '00019' ),
( '00022', 'EMP22', 'SD7', '00021' ),
( '00023', 'EMP23', 'SD8', '00021' ),
( '00024', 'EMP24', 'TL6', '00018' ),
( '00025', 'EMP25', 'SSD7', '00024' );
with cte as
(
select
EMPID ,
EMPNAME ,
EMPDESIG ,
MRGID ,
LEVEL = 0,
PATH = cast(EMPDESIG as varchar(8000))
from
#EMPMASTER
where
MRGID is null
UNION ALL
select
t.EMPID ,
t.EMPNAME ,
t.EMPDESIG ,
t.MRGID ,
LEVEL = cte.LEVEL + 1,
PATH = cast(cte.PATH + ' > '+ t.EMPDESIG as varchar(8000))
from
#EMPMASTER t
inner join cte on cte.EMPID = t.MRGID
)
select
EMPID ,
EMPNAME ,
EMPDESIG ,
MRGID ,
LEVEL ,
PATH ,
HIERARCHY = replicate(' ', LEVEL) + EMPDESIG
from
cte
order by
PATH;
The same but with the provided data samples:
declare #EMPMASTER table
(
EMPID CHAR(10) ,
EMPNAME NVARCHAR(50) ,
EMPDESIG VARCHAR(20) ,
MRGID CHAR(10)
);
insert into #EMPMASTER values
('1' , 'RAM' , 'CEO' , '0' ),
('7326' , 'MOHD RAFI' , 'MANAGER' , '7454' ),
('7454' , 'PMT PHARMA' , 'MANAGER' , '1' ),
('2094' , 'VAC SANJAY' , 'DEVELOPER' , '14005' ),
('602' , 'GS' , 'MANAGER' , '7454' ),
('412' , 'RAJESH' , 'LEAD' , '602' ),
('14005' , 'VAC SM N' , 'LEAD' , '7326' ),
('34395' , 'DEEPAK' , 'LEAD' , '7326' ),
('16430' , 'VIJAY' , 'DEVELOPER' , '34395' );
with cte as
(
select
EMPID ,
EMPNAME ,
EMPDESIG ,
MRGID ,
LEVEL = 0,
PATH = cast(EMPDESIG + ' (' + EMPNAME +')' as varchar(8000))
from
#EMPMASTER
where
MRGID = '0'
UNION ALL
select
t.EMPID ,
t.EMPNAME ,
t.EMPDESIG ,
t.MRGID ,
LEVEL = cte.LEVEL + 1,
PATH = cast(cte.PATH + ' > ' + t.EMPDESIG + ' (' + t.EMPNAME +')' as varchar(8000))
from
#EMPMASTER t
inner join cte on cte.EMPID = t.MRGID
)
select
EMPID ,
EMPNAME ,
EMPDESIG ,
MRGID ,
LEVEL ,
PATH ,
HIERARCHY = replicate(' ', LEVEL) + EMPDESIG + ' (' + EMPNAME +')'
from
cte
order by
PATH;
I have a problem with the request below!
REQUEST:
SELECT COALESCE(date(date_field), 'Total') AS "date_field_group",
COUNT( id_field ) AS "Nombre de bookings",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à l'achat",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à la vente",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) - SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS 'Marge',
CONCAT( REPLACE( FORMAT( (SUM( price2 ) / SUM( price1 ) ) , 2 ) , '1.', '' ) , ' ', '%') AS "Markup moyen"
FROM table1 S, table2 B
WHERE status_field
IN ( "1", "5")
AND DATE( date_field ) BETWEEN "2011-08-01" AND "2011-08-31"
AND type_field = "H"
AND price1 IS NOT NULL
AND S.id_field = B.id_field
AND B.id2 = "1"
GROUP BY date_field_group WITH ROLLUP
The thing is that the request is working fine (right numbers), but in the last line I was expected to get in first row "Total" and instead of that I got a field NULL...
Is someone know what is wrong with my request ?
Thx for any help ;).
You're query is almost correct (except for using implicit SQL '89 joins, which is an SQL anti-pattern)
The problem is in the last line: GROUP BY ... WITH ROLLUP.
The rollup gets applied very late in the process, after your COALESCE(date(date_field), 'Total').
So the coalesce has already finished by the time rollup comes along you need to rewrite the query like so:
SELECT COALESCE(date_field_group, 'Total') as date_field_group
, `Nombre de bookings`
, `Total à l'achat`
, `Total à la vente`
, `Marge`
, `Markup moyen`
FROM (
SELECT date(date_field) AS "date_field_group",
COUNT( id_field ) AS "Nombre de bookings",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à l'achat",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS "Total à la vente",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) - SUM( price1 ) , 2 ) , ',', ' ' ) , '.', ',' ) , ' €' ) AS 'Marge',
CONCAT( REPLACE( FORMAT( (SUM( price2 ) / SUM( price1 ) ) , 2 ) , '1.', '' ) , ' ', '%') AS "Markup moyen"
FROM table1 S
INNER JOIN table2 B ON (S.id_field = B.id_field)
WHERE status_field IN ( "1", "5")
AND DATE( date_field ) BETWEEN "2011-08-01" AND "2011-08-31"
AND type_field = "H"
AND price1 IS NOT NULL
AND B.id2 = "1"
GROUP BY date_field_group WITH ROLLUP ) AS subquery