Recursion in Mysql with as - mysql

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;

Related

Multiplying CASE row with different values

I'm creating a rating system. I have two tables hinne (rating) and hinnang (rating multiplier). I need to multiply the rating and then average the rating to know what rating I got out of all ratings by aine(subject).
Example:
All points need to be calculated in 0-100 point system.
So if my first rate is 25 and the rating multiplier is 4 then first rate (25/25)
4*25=100
If the second rate is 30 and multiplier 2 then second rate (30/50)
2*30=60
Now I need to average them like 100+60/2=80.
That should work in my SQL statement, but I got in trouble.
CASE
WHEN aine.nimetus = 'Füüsika I'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
So, this is my pivot case statement. hindamine.kaal should be different value for each hinne.tulemus 25*4,50*2 BUT it doesn't work. It just uses multiplier value 4. How can I make this work?
The result of SQL: 150
The expected result: 100
Therefore here is my full SQL:
SELECT
tudeng.m_number,hindamine.kaal, ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Füüsika I'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS FüüsikaI ,ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Kõrgem matemaatika I'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS KõrgemmatemaatikaI ,ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Raalprojekteerimine'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS Raalprojekteerimine ,ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Tehniline graafika'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS Tehnilinegraafika , ROUND(AVG(NULLIF(
CASE
WHEN aine.nimetus = 'Ettevõteluse alused'
THEN hinne.tulemus * hindamine.kaal
ELSE 0
END
,0)
))
AS Ettevõtelusealused
FROM
tudeng
INNER JOIN
aine_tudeng
ON
tudeng.tudeng_id = aine_tudeng.tudeng_id
INNER JOIN
aine
ON
aine.aine_id = aine_tudeng.aine_id
INNER JOIN
hinne
ON
hinne.aine_tudeng_id=aine_tudeng.aine_tudeng_id
INNER JOIN
hindamine
ON
hindamine.hindamine_id=aine_tudeng.aine_id
GROUP BY
tudeng.m_number
I suppose your error is here:
ON hindamine.hindamine_id = aine_tudeng.aine_id
A hindamine (assessment/rating?) is something different from an aine (subject?), so you are mistaken in joining on these IDs.
(I have used Google translator to help me with the meanings.)

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.

How to do a proper SQL recursion?

I'm currently working on a little error-handling issue in the following query:
declare #DayCounter int
declare #rows int
set #DayCounter = -2
set #rows = 0
while #rows = 0
begin
select
coalesce(p.name, case when len(ol.action)>1 then substring(ol.action,1,40)+'<br />'+substring(ol.action,41,80) else ca.code end) as description
, convert(varchar,DateAdd(minute,
15 * ((60 * Datepart(hour, latest_payment_status_change) +
Datepart(Minute, latest_payment_status_change)+
Case When DatePart(second, latest_payment_status_change) < 30
Then 7 Else 8 End) / 15),
DateAdd(day, DateDiff(day, 0, latest_payment_status_change), 0)),126) as date_time
, sum(num_of_persons) as num_tickets
from tick_order o
join tick_orderline ol on ol.order_id=o.id
join (
select olt.id
from tick_orderline_type olt
join tick_case ca on ca.id=olt.case_id
join tick_client tcl on tcl.id = ca.client_id
where tcl.id = 'CLIENT_TEST'
union
select orderline_type_id
from rpt_client_orderline_type rcot
join tick_client tcl on tcl.id = rcot.client_id
where tcl.id = 'CLIENT_TEST'
union
select olt.id
from tick_orderline_type olt
join rpt_client_case rcc on rcc.case_id=olt.case_id
join tick_client cl on cl.id=rcc.client_id
where cl.id = 'CLIENT_TEST'
) olt2 on olt2.id=ol.orderline_type_id
join tick_orderline_type olt on olt.id=ol.orderline_type_id
join tick_case ca on ca.id=olt.case_id
join tick_client cl on cl.id=ca.client_id
join tick_user_case uc on uc.case_id=ca.id
join tick_user u on u.id=uc.user_id
left join tick_promotion_code pc on pc.id=o.promotion_code_id
left join tick_promotion p on p.id=pc.promotion_id
where o.latest_payment_status_change>=dateadd(day,#DayCounter,current_timestamp)
and ((o.latest_payment_status_code = 'ORDER_PAYMENT_OK')
or (o.latest_payment_status_change > dateadd(minute,30,current_timestamp)
and o.latest_payment_status_code = 'ORDER_PAYMENT_WAITING' ))
group by
coalesce(p.name, case when len(ol.action)>1 then substring(ol.action,1,40)+'<br />'+substring(ol.action,41,80) else ca.code end)
, convert(varchar,DateAdd(minute,
15 * ((60 * Datepart(hour, latest_payment_status_change) +
Datepart(Minute, latest_payment_status_change)+
Case When DatePart(second, latest_payment_status_change) < 30
Then 7 Else 8 End) / 15),
DateAdd(day, DateDiff(day, 0, latest_payment_status_change), 0)),126)
order by 1,2
set #DayCounter = #DayCounter - 1;
if ##rowcount <> 0
begin
set #rows = ##rowcount;
print #DayCounter;
end;
end;
The data retrieved is used for a diagram that shows sales per sale-type from the past two days. What I'm trying to achieve now is: When no sales have been made in the past two days (##rowcount = 0), check back a day further each time until data has been found.
The query as it stands now returns something like this (I tried getting the image working, but I somehow am unable to; have a link instead):
https://www.dropbox.com/s/0hculuegrc88c69/SQL_Result.png?dl=0
And it doesn't stop, because for some reason the #rows variable stays 0, despite the query clearly returning rows. Even when using print ##rowcount it returns rows.
SO how do I fix this? Should I use a completely different method?
-Zubaja
It would seem I did not quite understood what my employer meant. He didn't want the error-handling in the SQL, but rather on the website: When no data is found for the past two days, simply show an empty diagram.

How to sum all titles even others are empty

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))

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 *