How to sum all titles even others are empty - mysql

my query objective is to sum all the fields from (3) tables but i have some problem in generating the final_total_sum output if some of the other titles empty the final_total_sum is empty....but if all titles are not empty my query generate final_total_sum(output).
I wan to do is even other titles are empty my query can still generate a final_total_sum(output).
http://s38.photobucket.com/user/eloginko/media/output_zpsfcab9d54.png.html
current query:
SELECT *,
ROUND(interview_sum +
other_sum +
edu_attain2_sum +
experience2_sum +
trainings2_sum +
eligibility2_sum) AS final_total_sum
FROM (
SELECT
ROUND((SELECT SUM(t2.inttotal)
FROM app_interview2 AS t2
WHERE t2.atic = t.atic)/7,1)
AS interview_sum,
ROUND((SELECT SUM(o2.ototal)
FROM other_app2 AS o2
WHERE o2.oaic = t.atic)/7,1)
AS other_sum,
ROUND((SELECT SUM(s1.edu_attain2)
FROM qual_stan2 AS s1
WHERE s1.oaic2 = t.atic)/7,1)
AS edu_attain2_sum,
ROUND((SELECT SUM(s2.experience2)
FROM qual_stan2 AS s2
WHERE s2.oaic2 = t.atic)/7,1)
AS experience2_sum,
ROUND((SELECT SUM(s3.trainings2)
FROM qual_stan2 AS s3
WHERE s3.oaic2 = t.atic)/7,1)
AS trainings2_sum,
ROUND((SELECT SUM(s4.eligibility2)
FROM qual_stan2 AS s4
WHERE s4.oaic2 = t.atic)/7,1)
AS eligibility2_sum,
t.atid,
t.atic,
t.atname,
t.region,
t.town,
t.uniq_id,
t.position,
t.salary_grade,
t.salary
FROM app_interview2 AS t
WHERE uniq_id = '$q'
GROUP BY t.atname
HAVING COUNT(DISTINCT t.atic)) subq

Try:
ROUND( ifnull(interview_sum,0) +
ifnull(other_sum,0) +
ifnull(edu_attain2_sum,0) +
ifnull(experience2_sum,0) +
ifnull(trainings2_sum,0) +
ifnull(eligibility2_sum,0)) AS final_total_sum
In SQL x + NULL always gives NULL, ifnull function converts nulls to 0

use like SUM(ifnull(t2.inttotal,0))

Related

Recursion in Mysql with as

There is a trip table with flights containing columns with the beginning and end of the route. It is necessary to organize a search for a route with several transfers. I can't figure out what my mistake is (error at line 21)?
with RoutesCTE as
(
select concat(airport_from + '->' + airport_to) as Route
,0 as TransfersCount
,airport_from
,airport_to
from trip
union all
select concat(r.Route + '->' + r1.airport_to) as Route
,TransfersCount + 1
,r.airport_from
,r1.airport_to
from RoutesCTE r
join trip r1
on r.airport_to = r1.airport_from
and r1.airport_to <> r.airport_from
and REGEXP_INSTR('%'+r1.airport_to+'%', r.Route) = 0
)
select Route
from RoutesCTE
where airport_from = 'MVO'
and airport_to = 'NOV'
and TransfersCount <= 2;

How to sort before using STUFF in SSRS

I have 2 different values I'm trying to STUFF here. It is Quantity + Price. For example: 1-$0.36; 100-$0.29; 25-$0.31. How can I have it sort by Quantity before being stuffed? (1,25,100 instead of 1,100,25) I did come across this link Sort data before concatenating using STUFF FOR XML, but it dealt with 1 value and I'm dealing with 2 values
SELECT STUFF(
(SELECT DISTINCT TOP (5)
'; ' + (CAST(FLOOR(CASE WHEN PCFBD.Quantity IS NOT NULL THEN PCFBD.Quantity ELSE 1 END) AS VARCHAR) + '-$' + CAST(REPLACE(REPLACE(RTRIM(REPLACE(
CASE WHEN PCF.PriceMethod = 0 THEN ROUND(I.CdCost / (100 - PCF.FormulaPercent) * 100, 2)
WHEN PCFBH.PriceFormula = 2 AND PCFBD.FormulaPercent IS NULL THEN ROUND(I.CdCost / (100 - PCF.FormulaPercent) * 100, 2)
WHEN PCFBH.PriceFormula = 2 AND PCFBD.FormulaPercent IS NOT NULL THEN ROUND(I.CdCost / (100 - PCFBD.FormulaPercent) * 100, 2)
WHEN PCFBH.PriceFormula = 1 THEN ROUND((I.ListPrice * (100 - PCFBD.FormulaPercent)) * .01,2)
ELSE NULL END, '000' ,'')), ' ','0') + '', '. ', '') AS VARCHAR))
FROM Item AS I
INNER JOIN PriceContractFamily AS PCF ON I.FamilyId = PCF.FamilyId
AND I.ItemStatus IN (0, 5)
INNER JOIN StockItem SI ON I.ItemId = SI.ItemId
AND SI.WarehouseId = '502E5876-C26B-4E11-8B88-AFE0C34ECF0D'
LEFT OUTER JOIN PriceContractFamilyBracketHeader AS PCFBH ON PCF.PriceContractFamilyId = PCFBH.PriceContractFamilyId
LEFT OUTER JOIN PriceContractFamilyBracketDetail AS PCFBD ON PCFBH.BracketHeaderId = PCFBD.BracketHeaderId
WHERE I.ListPrice = #ListPrice
AND LEFT(I.ItemNumber, 6) = #ItemNumber
AND PCF.PriceContractId = #PriceContractId
FOR XML PATH('')),1, 2, '') AS QtyPrice
You should be able to add an ORDER BY before the FOR XML PATH statement.

SUM selected columns using alias and group by

I'm trying to perform calculations on select columns using aliases and a grouping by. Query is below(problem on line before the from):
select r.res_id,
r.arrive_date,
r.depart_date,
r.res_type,
if(DATEDIFF(r.depart_date, r.arrive_date) >29, 'LT', 'ST') as 'StayType',
SUM(r.rent + r.fee_arr_early + r.fee_dep_late + r.fee_peace_waiver + r.fee_pool + r.city_tax + r.fee_cleaning + r.fee_pet + r.fee_tshirt + r.fee_misc + r.fee_non_tax + r.fee_processing + r.fee_travel_ins + r.fee_event + r.fee_cancel) as 'folioTotal',
coalesce((select SUM(g.amount) from guest_payments as g where g.resId = r.res_id and charge_type = 'charge' and approved = 'Y'),0) as 'payments',
coalesce((select SUM(g.amount) from guest_payments as g where g.resId = r.res_id and charge_type = 'credit' and approved = 'Y'),0) as 'credits',
(SUM('folioTotal') - SUM('payments') + SUM('credits')) as 'folioBalance'
from reservations as r
join guest_payments as g
on r.res_id = g.resId
group by r.res_id
I've tried putting this inside another sum with the same outcome.
I was being stupid, I was referencing the aliases inside single ticks which is why it wasn't calculating. Solution:
select r.res_id,
r.arrive_date,
r.depart_date,
r.res_type,
g.entry_date,
if(DATEDIFF(r.depart_date, r.arrive_date) >29, 'LT', 'ST') as 'StayType',
(select SUM(r.rent + r.fee_arr_early + r.fee_dep_late + r.fee_peace_waiver + r.fee_pool + r.city_tax + r.fee_cleaning + r.fee_pet + r.fee_tshirt + r.fee_misc + r.fee_non_tax + r.fee_processing + r.fee_travel_ins + r.fee_event + r.fee_cancel) from reservations as r where r.res_id = g.resId) as 'folioTotal',
coalesce((select SUM(g.amount) from guest_payments as g where g.resId = r.res_id and charge_type = 'charge' ),0) as 'payments',
coalesce((select SUM(g.amount)* -1 from guest_payments as g where g.resId = r.res_id and charge_type = 'credit' and approved = 'Y'),0) as 'credits',
(select folioTotal - payments + credits)
from reservations as r
join guest_payments as g
on r.res_id = g.resId
group by r.res_id

How to replace NULL with empty string in SQL?

I am using below query to fetch column value by comma separated.
(SELECT STUFF ((SELECT ',' + CAST(Proj_ID AS VARCHAR) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE()) AND PROJ_LFCYC_STA_CD = 'A' AND
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '')
AS Enter_Date)
Can anyone guide me to replace null value by empty string here.
Updated:
(SELECT STUFF ((SELECT ',' + coalesce( CAST(Proj_ID AS VARCHAR), '' ) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE()) AND PROJ_LFCYC_STA_CD = 'A' AND
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '')
AS Enter_Date)
Try IsNull
select ISNULL(Column,'') as ColumnName
OR COALESCE
select COALESCE(NULLIF(ColumnName,''), 'Column')
An example from the AdventureWorks database
select e.ModifiedDate, ISNULL(p.FirstName,'') as FirstName
from Person.BusinessEntity as e
left join Person.Person as p on e.BusinessEntityID = p.BusinessEntityID
By using this, if there are no matching Person records, the FirstName will be displayed as an empty string instead of NULL
You can white out null values with the coalesce function
select coalesce(MyColumn, '')
Coalesce takes any number of columns or constants and returns the first one which isn't null.
Your query would be:
(SELECT STUFF ((SELECT ',' + convert(varchar, coalesce( Proj_ID, '' )) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE()) AND PROJ_LFCYC_STA_CD = 'A' AND
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '')
AS Enter_Date)

SSRS Subscriptions - How to view ALL report recipients

I've written an SSRS report to help me keep track of SSRS subscriptions. I've repurposed a script that will use Reportserver.dbo.Subscriptions.LastStatus to view email recipients, however, it will only list the first 520 characters of LastStatus. Because some of our distribution lists are quite large, some of the names that my script searches for are not being found (even though they are part of the distribution). Below is the script that I am using:
SELECT Reportname = c.Name
,FileLocation = c.Path
,SubscriptionDesc=su.Description
,Subscriptiontype=su.EventType
,su.LastStatus
,su.LastRunTime
,Schedulename=sch.Name
,ScheduleType = sch.EventType
,ScheduleFrequency =
CASE sch.RecurrenceType
WHEN 1 THEN 'Once'
WHEN 2 THEN 'Hourly'
WHEN 4 THEN 'Daily/Weekly'
WHEN 5 THEN 'Monthly'
END
,su.Parameters
FROM Reportserver.dbo.Subscriptions su
JOIN Reportserver.dbo.Catalog c
ON su.Report_OID = c.ItemID
JOIN Reportserver.dbo.ReportSchedule rsc
ON rsc.ReportID = c.ItemID
AND rsc.SubscriptionID = su.SubscriptionID
JOIN Reportserver.dbo.Schedule Sch
ON rsc.ScheduleID = sch.ScheduleID
WHERE LastStatus like #Email
ORDER BY LastRunTime DESC
Any code that I have found online uses the LastStatus column to display this data. If anyone has any suggestions as to a more complete way for me to list all of the members of the report distribution list, I would appreciate it.
Below is SQL to query for the full text of the subscription parameters. I think this will work with extremely long address lists, but I don't have a test server with long address lists available right now.
If using this in production, I'd probably throw in a couple of WITH ( NOLOCK )'s and wouldn't expect support from MS on problems.
;
WITH subscriptionXmL
AS (
SELECT
SubscriptionID ,
OwnerID ,
Report_OID ,
Locale ,
InactiveFlags ,
ExtensionSettings ,
CONVERT(XML, ExtensionSettings) AS ExtensionSettingsXML ,
ModifiedByID ,
ModifiedDate ,
Description ,
LastStatus ,
EventType ,
MatchData ,
LastRunTime ,
Parameters ,
DeliveryExtension ,
Version
FROM
ReportServer.dbo.Subscriptions
),
-- Get the settings as pairs
SettingsCTE
AS (
SELECT
SubscriptionID ,
ExtensionSettings ,
-- include other fields if you need them.
ISNULL(Settings.value('(./*:Name/text())[1]', 'nvarchar(1024)'),
'Value') AS SettingName ,
Settings.value('(./*:Value/text())[1]', 'nvarchar(max)') AS SettingValue
FROM
subscriptionXmL
CROSS APPLY subscriptionXmL.ExtensionSettingsXML.nodes('//*:ParameterValue') Queries ( Settings )
)
SELECT
*
FROM
SettingsCTE
WHERE
settingName IN ( 'TO', 'CC', 'BCC' )
I also found this query from SQL Server MSDN Social;
Original Query Author MSDN Profile: Sandip Shinde
SELECT
c.Name AS ReportName,
'Next Run Date' = CASE next_run_date
WHEN 0 THEN null
ELSE
substring(convert(varchar(15),next_run_date),1,4) + '/' +
substring(convert(varchar(15),next_run_date),5,2) + '/' +
substring(convert(varchar(15),next_run_date),7,2)
END,
'Next Run Time' = isnull(CASE len(next_run_time)
WHEN 3 THEN cast('00:0'
+ Left(right(next_run_time,3),1)
+':' + right(next_run_time,2) as char (8))
WHEN 4 THEN cast('00:'
+ Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
WHEN 5 THEN cast('0' + Left(right(next_run_time,5),1)
+':' + Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
WHEN 6 THEN cast(Left(right(next_run_time,6),2)
+':' + Left(right(next_run_time,4),2)
+':' + right(next_run_time,2) as char (8))
END,'NA'),
Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="TO"])[1]','nvarchar(50)') as [To]
,Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="CC"])[1]','nvarchar(50)') as [CC]
,Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="RenderFormat"])[1]','nvarchar(50)') as [Render Format]
,Convert(XML,[ExtensionSettings]).value('(//ParameterValue/Value[../Name="Subject"])[1]','nvarchar(50)') as [Subject]
---Example report parameters: StartDateMacro, EndDateMacro & Currency.
,Convert(XML,[Parameters]).value('(//ParameterValue/Value[../Name="StartDateMacro"])[1]','nvarchar(50)') as [Start Date]
,Convert(XML,[Parameters]).value('(//ParameterValue/Value[../Name="EndDateMacro"])[1]','nvarchar(50)') as [End Date]
,Convert(XML,[Parameters]).value('(//ParameterValue/Value[../Name="Currency"])[1]','nvarchar(50)') as [Currency]
,[LastStatus]
,[EventType]
,[LastRunTime]
,[DeliveryExtension]
,[Version]
FROM
dbo.[Catalog] c
INNER JOIN dbo.[Subscriptions] S ON c.ItemID = S.Report_OID
INNER JOIN dbo.ReportSchedule R ON S.SubscriptionID = R.SubscriptionID
INNER JOIN msdb.dbo.sysjobs J ON Convert(nvarchar(128),R.ScheduleID) = J.name
INNER JOIN msdb.dbo.sysjobschedules JS ON J.job_id = JS.job_id
According to MS (https://learn.microsoft.com/en-us/sql/reporting-services/subscriptions/manage-subscription-owners-and-run-subscription-powershell?view=sql-server-ver16), you can also use this powershell command:
$webSRV = New-WebServiceProxy -Uri "http://myservername/ReportServer/ReportService2010.asmx" -Namespace SSRS.ReportingService2010 -UseDefaultCredential;
$mySubsList = $webSRV.ListSubscriptions("/");
$mySubsList | select *