Convert SQL query to Eloquent Laravel with many join - mysql

How do I convert this query to Eloquent syntax
select *
from
( select f85
, f86
, f87
, f88
, v1_position_id
, v1_companyuser_id
, v89.position_value f89
from
( select f85
, f86
, f87
, v1_position_id
, v1_companyuser_id
, v88.position_value f88
from
( select f85
, f86
, v1_position_id
, v1_companyuser_id
, v87.position_value f87
from
( select f85
, v1_position_id
, v1_companyuser_id
, v86.position_value f86
from
( SELECT v1.position_id v1_position_id
, v1.companyuser_id v1_companyuser_id
, v1.position_value f85
FROM all_position_template_with_data v1
WHERE v1.position_id = 25
AND companyuser_id = 1
AND position_template_id = 85
) v1
join all_position_template_with_data v86
on v1_position_id = v86.position_id
AND v1_companyuser_id = v86.companyuser_id
AND v86.position_template_id = 86
) v86
join all_position_template_with_data v87
on v1_position_id = v87.position_id
AND v1_companyuser_id = v87.companyuser_id
AND v87.position_template_id = 87
) v87
join all_position_template_with_data v88
on v1_position_id = v88.position_id
AND v1_companyuser_id = v88.companyuser_id
AND v88.position_template_id = 88
) v88
join all_position_template_with_data v89
on v1_position_id = v89.position_id
AND v1_companyuser_id = v89.companyuser_id
AND v89.position_template_id = 89
) v89

Related

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.

Join error in using CTE in Hive

i have two queries which are doing almost the similar work.
One does it without CTEs and one with CTEs. I am unable to figure out why the second query is giving absolutely no results while the first one is.
I have spent the last two hours trying to figure this out by trying out various joins and the same joins working in query 1 are not working in query 2. I hope someone can guide me with this.
First query (Returns results):
WITH MessageCTE AS
(
SELECT dt
, id
, ts
, family
, message_type
, to_user
, message_id
, class
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02 as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
SELECT COUNT(DISTINCT to_user) AS Users
, AVG(latency) AS AvgLatency
, AVG(CASE WHEN latency > 0 THEN latency ELSE NULL END) AS AvgLatency_Positive
, PERCENTILE(latency, 0.5) AS 50Percentile
, PERCENTILE(latency, 0.75) AS 75Percentile
, PERCENTILE(latency, 0.8) AS 80Percentile
, PERCENTILE(latency, 0.9) AS 90Percentile
, PERCENTILE(latency, 0.95) AS 95Percentile
, PERCENTILE(latency, 0.99) AS 99Percentile
FROM
(
SELECT a.dt, a.to_user, (latency_dl.ts - latency_pb.ts) as latency
FROM
(
SELECT dt
, id, ts
, family
, message_type
, to_user
, message_id
, class
FROM MessageCTE
WHERE class = 'pb'
) as latency_pb
INNER JOIN
(SELECT dt
, id
, ts
, family
, message_type
, to_user
, message_id
, class
FROM MessageCTE
WHERE class = 'rdl'
AND family = 'stm'
) as latency_rdl
ON latency_pb.dt = latency_rdl.dt and latency_pb.to_user = latency_rdl.to_user and latency_pb.id = latency_rdl.id
INNER JOIN
(
SELECT dt
, id
, ts
, family
, message_type
, to_user
, message_id
, class
FROM MessageCTE
WHERE class = 'dl'
) as latency_dl
ON latency_rdl.dt = latency_dl.dt and latency_rdl.to_user = latency_dl.to_user and latency_rdl.id = latency_dl.id) AS UserLatency;
First Query Output:
Now Second Query, is a slight modification and all the same conditions, but for some reason it is returning no matches. Hopefully someone can guide me out, i just spent around 2 hours trying some joins out and i am unable to figure out why they are not happening.
Second Query:
WITH MessageCTE_pb AS
(
SELECT dt, id, ts, to_user
FROM
(
SELECT dt, id, min(ts) as ts, to_user
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02
WHERE class = 'pb'
GROUP BY dt, to_user, id
) as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
, MessageCTE_dl AS
(
SELECT dt, id, ts, to_use
FROM
(
SELECT dt, id, max(ts) as ts, to_user
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02
WHERE class = 'dl'
GROUP BY dt, to_user, id
) as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
, MessageCTE_rdl AS
(
SELECT dt, id, to_user
FROM
(
SELECT DISTINCT dt, id, to_user
FROM dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02
WHERE class = 'rdl'
AND family = 'stm'
) as latencydata
INNER JOIN dhruv.UsersOn503AndAbove_20171201_200k as required_users
ON latencydata.to_user = required_users.user_id
)
SELECT COUNT(DISTINCT to_user) AS Users
, AVG(latency) AS AvgLatency
, AVG(CASE WHEN latency > 0 THEN latency ELSE NULL END) AS AvgLatency_Positive
, PERCENTILE(latency, 0.5) AS 50Percentile
, PERCENTILE(latency, 0.75) AS 75Percentile
, PERCENTILE(latency, 0.8) AS 80Percentile
, PERCENTILE(latency, 0.9) AS 90Percentile
, PERCENTILE(latency, 0.95) AS 95Percentile
, PERCENTILE(latency, 0.99) AS 99Percentile
FROM
(
SELECT a.dt, a.to_user, (latency_dl.ts - latency_pb.ts) as latency
FROM MessageCTE_pb as latency_pb
INNER JOIN MessageCTE_rdl as latency_rdl
ON latency_pb.dt = latency_rdl.dt and latency_pb.to_user = latency_rdl.to_user and latency_pb.id = latency_rdl.id
INNER JOIN MessageCTE_dl as latency_dl
ON latency_rdl.dt = latency_dl.dt and latency_rdl.to_user = latency_dl.to_user and latency_rdl.id = latency_dl.id) AS UserLatency;
Thanks!
Second Query Result:
Another comment in an answer block so I can post a bunch of SQL...
What is the result of this?
WITH
UserLatency AS
(
SELECT
latencydata.dt,
latencydata.to_user,
latencydata.id,
MAX(CASE WHEN latencydata.class = 'dl' THEN latencydata.ts END)
-
MIN(CASE WHEN latencydata.class = 'pb' THEN latencydata.ts END)
AS latency
FROM
dhruv.MessageLatencyInformation_20171210_20171125_to_20171130_02 AS latencydata
INNER JOIN
dhruv.UsersOn503AndAbove_20171201_200k AS required_users
ON latencydata.to_user = required_users.user_id
GROUP BY
latencydata.dt,
latencydata.to_user,
latencydata.id
HAVING
0 < SUM(CASE WHEN latencydata.class = 'rdl'
AND latencydata.family = 'stm' THEN 1 END)
)
SELECT
COUNT(DISTINCT to_user) AS Users
, AVG(latency) AS AvgLatency
, AVG(CASE WHEN latency > 0 THEN latency END) AS AvgLatency_Positive
, PERCENTILE(latency, 0.50) AS 50Percentile
, PERCENTILE(latency, 0.75) AS 75Percentile
, PERCENTILE(latency, 0.80) AS 80Percentile
, PERCENTILE(latency, 0.90) AS 90Percentile
, PERCENTILE(latency, 0.95) AS 95Percentile
, PERCENTILE(latency, 0.99) AS 99Percentile
FROM
UserLatency
;

MySQL - structure a query with different values that requires a lookup from the same table

This is my query:
SELECT f.pending
, f.title
, f.funeraltype
, f.firstname
, f.middlename
, f.lastname
, f.suffix
, f.displayage
, f.age
, f.displaycity
, f.city
, f.displaydate
, f.date
, f.aftersunset
, f.funeraldate
, f.displayfuneraldate
, f.ftime
, f.displayservicelocation
, l.location
, f.displaycemetery
, c.name
, f.displayobituary
, f.obituary
, f.displaycharity1
, ch.name
, f.charity1memo
, f.displaycharity2
, f.charity2
, f.charity2memo
, f.displaycharity3
, f.charity3
, f.charity3memo
, f.displaycharity4
, f.charity4
, f.charity4memo
, f.displaycharity5
, f.charity5
, f.charity5memo
, f.memorialbook
, f.displayshiva
, f.displaytime
, f.shivaendpart
, f.shivauntil
, f.shivaatresidence
, f.shivaname
, f.shivaaddress
, f.shivacity
, f.shivastate
, f.shivazip
, f.shivaphone
, f.shivacomment
, f.displayfamilymembers
, f.familymembers
, f.displayclergy
, f.clergy
, f.livevideo
, f.archivevideo
, f.video
, f.usemp4video
, f.mp4video
, f.custom_text
, f.charities_footnote
, f.charity1note
, f.charity2note
, f.charity3note
, f.charity4note
, f.charity5note
FROM funerals f
, locations l
, cemeteries c
, charities ch
WHERE f.servicelocation = l.locationid
AND f.cemetery = c.cemeteryID
AND f.charity1 = ch.CharityID
AND f.charity2 = ch.CharityID
AND f.charity3 = ch.CharityID
AND f.charity4 = ch.CharityID
AND f.charity5 = ch.CharityID
ch.name is what I'm looking to extract. f.charity1, f.charity2, f.charity3, f.charity4, & f.charity5 all contain different IDs that require a lookup in the 'charities' table. How would I structure this query to display each charity name?
SELECT f.pending
, l.location
, f.displaycemetery
, c.name
, f.displaycharity1
, ch.name
, f.charity1memo
, f.displaycharity2
, f.charity2
, f.charity2memo
, f.displaycharity3
, f.charity3
, f.charity3memo
, f.displaycharity4
, f.charity4
, f.charity4memo
, f.displaycharity5
, f.charity5
, f.charity5memo
, f.charity1note
, f.charity2note
, f.charity3note
, f.charity4note
, f.charity5note
FROM funerals f
JOIN locations l
ON l.locationid = f.servicelocation
JOIN cemeteries c
ON c.cemeteryID = f.cemetery
JOIN charities ch1
ON ch1.CharityID = f.charity1
JOIN charities ch2
ON ch2.CharityID = f.charity2
etc.
try this:
SELECT
f.pending
, f.title
, f.funeraltype
, f.firstname
, f.middlename
, f.lastname
, f.suffix
, f.displayage
, f.age
, f.displaycity
, f.city
, f.displaydate
, f.date
, f.aftersunset
, f.funeraldate
, f.displayfuneraldate
, f.ftime
, f.displayservicelocation
, l.location
, f.displaycemetery
, c.name
, f.displayobituary
, f.obituary
, f.displaycharity1
, ch1.name
, ch2.name
, ch3.name
, ch4.name
, ch5.name
, f.charity1memo
, f.displaycharity2
, f.charity2
, f.charity2memo
, f.displaycharity3
, f.charity3
, f.charity3memo
, f.displaycharity4
, f.charity4
, f.charity4memo
, f.displaycharity5
, f.charity5
, f.charity5memo
, f.memorialbook
, f.displayshiva
, f.displaytime
, f.shivaendpart
, f.shivauntil
, f.shivaatresidence
, f.shivaname
, f.shivaaddress
, f.shivacity
, f.shivastate
, f.shivazip
, f.shivaphone
, f.shivacomment
, f.displayfamilymembers
, f.familymembers
, f.displayclergy
, f.clergy
, f.livevideo
, f.archivevideo
, f.video
, f.usemp4video
, f.mp4video
, f.custom_text
, f.charities_footnote
, f.charity1note
, f.charity2note
, f.charity3note
, f.charity4note
, f.charity5note
FROM funerals f
INNER JOIN locations l on f.servicelocation = l.locationid
INNER JOIN cemeteries c ON f.cemetery = c.cemeteryID
INNER JOIN charities ch1 ON f.charity1 = ch1.CharityID
INNER JOIN charities ch2 ON f.charity2 = ch2.CharityID
INNER JOIN charities ch3 ON f.charity3 = ch3.CharityID
INNER JOIN charities ch4 ON f.charity4 = ch4.CharityID
INNER JOIN charities ch5 ON f.charity5 = ch5.CharityID

Combining Two SQL Select Queries with Where Clauses

I have two Oracle queries that I need combined through an inner join where the tables are joined using the person_uid field. This is because I need to compare what an employee's pay, job title, and supervisor was from one year to the next. I need to have the 2015 data and the 2014 data in the same row for each employee, so if this can be done by doing a subquery using an inner join on the person_uid field, that is the method that I believe will accomplish this.
Here is the first query that pulls the necessary 2015 data:
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE posn.position_contract_type = 'P'
AND posn.position_status <> 'T'
AND posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
AND p2.position = posn.position
AND p2.job_suffix = posn.job_suffix
AND p2.effective_date <= '01-Nov-2015')
order by person_uid
I need it to be joined to this query on the person_uid field so that each unique ID for the employee has the records for both years in a single row:
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE posn.position_contract_type = 'P'
AND posn.position_status <> 'T'
AND posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
AND p2.position = posn.position
AND p2.job_suffix = posn.job_suffix
AND p2.effective_date <= '01-Nov-2014')
order by person_uid
An easy way would be to use OR:
WHERE posn.position_contract_type = 'P' AND
posn.position_status <> 'T' AND
(posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
p2.position = posn.position AND
p2.job_suffix = posn.job_suffix AND
p2.effective_date <= '01-Nov-2014'
) OR
posn.effective_date = (SELECT MAX(effective_date)
FROM employee_position_cunm p2
WHERE p2.person_uid = posn.person_uid
p2.position = posn.position AND
p2.job_suffix = posn.job_suffix AND
p2.effective_date <= '01-Nov-2015'
)
)
In Oracle you could do a UNION or a UNION ALL.
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE ...
...
...
UNION ALL
SELECT person_uid,
id ,
position_contract_type,
position,
job_suffix,
position_status,
effective_date,
position_employee_class,
timesheet_organization ,
appointment_pct ,
annual_salary ,
per_pay_salary ,
hourly_rate ,
position_title ,
academic_title ,
supervisor_id ,
supervisor_name ,
supervisor_position ,
supervisor_job_suffix ,
supervisor_title ,
assignment_grade ,
position_change_reason ,
position_change_reason_desc
FROM employee_position_cunm posn
WHERE ....
....
....;

how to calculate from each row value in sql

I have a table named general_ledger from which I need to show dr_amount, cr_amount and the balance between them as running_balance. That's why I have written a query that is given below. But I am getting the result of each query like the balance only of current row. But I need to produce the result with the remaining balance. Suppose First row dr_balance is 20000 and cr_balance is 5000 and remaining balance is 15000. In second row only cr_balance is 5000. Now the result should be 10000 with the deduction but my result is -5000. I have no idea how to fix this. Can anyone please help me on this? I need your help very much. Here is my query given below :
SELECT '' AS cost_center_id
, '' AS cost_center_name
, '' AS office_code
, CONVERT('2013-02-01',DATETIME) AS transaction_date
, '' AS accounts_head_id
, '' AS account_name
, '' AS opposite_accounts_head_id
, '' AS opposite_account_name
, 'Opening Balance' AS particulars
, tempOpeningBalance.dr_amount
, tempOpeningBalance.cr_amount
, '' AS voucher_no
, '' AS vin
FROM (SELECT IFNULL(mcoa.account_code,'1101010101100321') AS account_code
, IFNULL(mcoa.account_name,'Cash') AS account_name
, IFNULL(mcoa.account_type,'ASSET') AS accountType
, CAST(IFNULL(SUM(IFNULL(maingl.dr_balance,0)),0) AS DECIMAL(27,5)) AS dr_amount
, CAST(IFNULL(SUM(IFNULL(maingl.cr_balance,0)),0) AS DECIMAL(27,5)) AS cr_amount
FROM master_chart_of_accounts AS mcoa
INNER JOIN chart_of_accounts AS coa ON (mcoa.id = coa.master_chart_of_accounts_id AND mcoa.id = 80)
LEFT JOIN general_ledger AS maingl ON (coa.id = maingl.accounts_head_id AND coa.account_code='1101010101100321')
INNER JOIN
( SELECT gl.accounts_head_id, MAX(gl.gl_id) AS max_gl_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
FROM general_ledger AS gl
-- INNER JOIN voucher_info AS vi ON (gl.voucher_info_id = vi.id)
-- WHERE vi.posting_date < '2013-02-01' AND
WHERE gl.transaction_date < '2013-02-01' AND
gl.cost_center_id IN ('BI0000000000000000000001') AND
gl.country_id IN (1) AND
gl.office_code IN ('UG500013') AND
1=1
GROUP BY gl.accounts_head_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
ORDER BY gl.accounts_head_id
) AS tmpgl
ON ( maingl.office_code = tmpgl.office_code
AND maingl.office_type = tmpgl.office_type
AND maingl.accounts_head_id = tmpgl.accounts_head_id
AND maingl.country_id = tmpgl.country_id
AND maingl.cost_center_id = tmpgl.cost_center_id
AND maingl.gl_id = tmpgl.max_gl_id
)
WHERE mcoa.account_status_id = 1 AND
coa.account_status_id = 1
) AS tempOpeningBalance
UNION
SELECT vi.cost_center_id
, cc.center_name AS cost_center_name
, gl.office_code
, vi.posting_date AS transaction_date
, vd.accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.accounts_head_id) AS account_name
, vd.opposite_accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.opposite_accounts_head_id) AS opposite_account_name
, vd.particulars
, gl.dr_amount AS dr_amount -- here to check
, gl.cr_amount AS cr_amount
, vi.voucher_no
, vi.vin
FROM general_ledger AS gl
INNER JOIN voucher_info AS vi
ON (gl.voucher_info_id = vi.id)
INNER JOIN cost_center AS cc
ON (vi.cost_center_id = cc.id)
INNER JOIN voucher_details AS vd
ON (vi.id = vd.voucher_info_id)
INNER JOIN chart_of_accounts AS coa
ON (vd.accounts_head_id = coa.id)
WHERE vi.posting_date BETWEEN '2013-02-01' AND'2013-02-28'
AND vi.voucher_status_id = 3
AND vd.status_id = 1
AND vi.office_code = 'UG500063'
AND coa.account_code='1101010101100321'
AND coa.cost_center_id = 'BI0000000000000000000001'
ORDER BY cost_center_name
, office_code
, transaction_date;
Use a variable like this
SET #running_balance=0;
SELECT dr_amount AS dr_amount
, cr_amount AS cr_amount
, #running_balance := (#running_balance + dr_amount - cr_amount)
FROM general_ledger