SQL - Filtering the Duplicate - sql-server-2008

I have a sql Query working fine but not able to generate accurate result
My Query Details as follows :
declare #test varchar(500)
SELECT #test=coalesce(#test+',','') + cast(RoleName as varchar) FROM
( select roles.RoleName from LU_BCOMS_usersroles usrroles
inner join LU_BCOMS_roles roles
on roles.roleid = usrroles.Roles_roleid
where Users_Userid='MV10310'
) as Tbl
select repfamily.ProductName as Category,repfamily.Family as SeqChange,repfamily.RepFamily as DescOfChange, req.*,
TaskCompVer =
CASE WHEN req.UpdateByASPM is not null THEN 'Provide PLQM Wish List'
WHEN req.UpdateByASPM is null THEN 'Provide ASPM Wish List'
WHEN req.CreatedBy is not null THEN 'Provide ASPM Wish List'
END
from performa.TX_BCOMS_Request as req
inner join TX_BCOMS_Requestrepfamily family on
family.request_requestid=req.requestid
inner join LU_BCOMS_RepFamily as repfamily on
family.RepFamily_repFamilyid=repfamily.repfamilyid
where req.UpdatedByPLQM is null and (
((CHARINDEX('ASPM',#test)> 0 and CHARINDEX('PLQM',#test)> 0) and req.UpdatedByPLQM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM',#test)> 0 ) and req.UpdateByASPM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM' ,#test)< 0 and CHARINDEX('PLQM',#test) < 0) and req.CreatedBy IS null)
)
Output :
Caterogy SeqCategory DescofChange RequestId TaskCompVer
BIGBEAR BIGBEAR BIGBEAR B14020002 Provide ASPM Wish List
ARCUS3PL KOJN-RE ARCUS3PL B14020002 Provide ASPM Wish List
AURORA Aurora Aurora B14020003 Provide ASPM Wish List
When requestId and TaskCompVer are same there is no need to show 2 records, have to filter something like below..
I need output like below :
Output :
Caterogy SeqCategory DescofChange RequestId TaskCompVer
BIGBEAR,ARCUS3PL BIGBEAR,KOJN-RE BIGBEAR,ARCUS3PL B14020002 Provide ASPM Wish List
AURORA Aurora Aurora B14020003 Provide ASPM Wish List
I need to display the actual as above I tried using STUFF function cannot able to generate the actual output...

May it helpful for you.
CREATE TABLE tempTable(name VARCHAR(50),subjects VARCHAR(50),phone VARCHAR(50))
INSERT INTO tempTable VALUES
('siddique','CRM','123456'),('siddique','Asp.net','9874563'),
('siddique','sql server','44451685'),('Danish','MVC','123456'),
('Danish','sql server','9874563'),('Danish','WCF','44451685'),
('shah g','Account','123456'),('shah g','MBA','9874563'),
('shah g','Math','44451685')
Your simple query select all data
SELECT * FROM tempTable
name subjects phone
siddique CRM 123456
siddique Asp.net 9874563
siddique sql server 44451685
Danish MVC 123456
Danish sql server 9874563
Danish WCF 44451685
shah g Account 123456
shah g MBA 9874563
shah g Math 44451685
Using STUFF to comma seperate your values agaist each name (GROUP BY name)
SELECT
name
,STUFF((SELECT ', ' + subjects
FROM tempTable temp2 WHERE temp2.name=temp1.name
FOR XML PATH('')), 1, 1, '') AS subjects
,STUFF((SELECT '; ' + phone
FROM tempTable temp2 WHERE temp2.name=temp1.name
FOR XML PATH('')), 1, 1, '') AS phones
FROM tempTable temp1
GROUP BY name
DROP TABLE tempTable
Output:
name subjects phones
Danish MVC, sql server, WCF 123456; 9874563; 44451685
shah g Account, MBA, Math 123456; 9874563; 44451685
siddique CRM, Asp.net, sql server 123456; 9874563; 44451685

I needed a similar Query where i needed it the same way... Here is My Query:
SELECT
'All Users' as QuestionOption,
Stuff( (SELECT N'; ' + email FROM users where email>=' ' FOR XML PATH(''),TYPE)
.value('text()[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue
UNION
SELECT 'All Volunteers' as QuestionOption, Stuff( (SELECT N'; ' + U.email FROM
dbo.Users AS U LEFT OUTER JOIN (SELECT up.UserID, MAX(CASE WHEN ppd.PropertyName = \
'Volunteer' THEN up.PropertyValue ELSE '' END) AS Volunteer
FROM
dbo.UserProfile AS up
INNER JOIN dbo.ProfilePropertyDefinition AS ppd ON
up.PropertyDefinitionID = ppd.PropertyDefinitionID and ppd.PortalID = 0 Group By
up.UserID) as upd on U.UserID = upd.UserID Where upd.Volunteer='True' FOR XML
PATH(''),TYPE) .value('text()[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue
UNION
SELECT 'All Committees' as QuestionOption, Stuff( (SELECT N'; ' + U.email FROM
dbo.USERS AS U LEFT OUTER JOIN (SELECT up.UserID, MAX(CASE WHEN ppd.PropertyName =
'Committee' THEN up.PropertyValue ELSE '' END) AS Committee FROM dbo.UserProfile AS
up INNER JOIN dbo.ProfilePropertyDefinition AS ppd ON up.PropertyDefinitionID =
ppd.PropertyDefinitionID and ppd.PortalID = 0 Group By up.UserID) as upd on U.UserID
= upd.UserID Where upd.Committee >' ' FOR XML PATH(''),TYPE) .value('text()
[1]','nvarchar(max)'),1,2,N'') as QuestionOptionValue
Im not the best at writing them, so you could use mine as an example. my output is:
QuestionOption QuestionOptionValue
All Committees Email#email.com; email#email.com
All Users Email#email.com; email#email.com
All Volunteers Email#email.com; email#email.com
I hope this helps you!

try this,,,,
declare #test varchar(500)
SELECT #test=coalesce(#test+',','') + cast(RoleName as varchar) FROM
( select roles.RoleName from LU_BCOMS_usersroles usrroles
inner join LU_BCOMS_roles roles
on roles.roleid = usrroles.Roles_roleid
where Users_Userid='MV10310'
) as Tbl
select
req.*,
TaskCompVer =
CASE WHEN req.UpdateByASPM is not null THEN 'Provide PLQM Wish List'
WHEN req.UpdateByASPM is null THEN 'Provide ASPM Wish List'
WHEN req.CreatedBy is not null THEN 'Provide ASPM Wish List'
END,
STUFF(
(
select ','+repfamily.ProductName
from TX_BCOMS_Requestrepfamily family
inner join LU_BCOMS_RepFamily as repfamily on family.RepFamily_repFamilyid=repfamily.repfamilyid
where family.request_requestid=req.requestid
FOR XML PATH('') ), 1, 1, '' ) as 'Category',
STUFF(
(
select ','+repfamily.Family
from TX_BCOMS_Requestrepfamily family
inner join LU_BCOMS_RepFamily as repfamily on family.RepFamily_repFamilyid=repfamily.repfamilyid
where family.request_requestid=req.requestid
FOR XML PATH('') ), 1, 1, '' ) as 'SeqChange',
STUFF(
(
select ','+repfamily.RepFamily
from TX_BCOMS_Requestrepfamily family
inner join LU_BCOMS_RepFamily as repfamily on family.RepFamily_repFamilyid=repfamily.repfamilyid
where family.request_requestid=req.requestid
FOR XML PATH('') ), 1, 1, '' ) as 'DescOfChange' ,
repfamily.ProductName as Category,repfamily.Family as SeqChange,repfamily.RepFamily as DescOfChange,
from performa.TX_BCOMS_Request as req
where req.UpdatedByPLQM is null and (
((CHARINDEX('ASPM',#test)> 0 and CHARINDEX('PLQM',#test)> 0) and req.UpdatedByPLQM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM',#test)> 0 ) and req.UpdateByASPM IS null)
or
((CHARINDEX('PLQM' ,#test)> 0) and req.UpdateByASPM IS NOT null)
or
((CHARINDEX('ASPM' ,#test)< 0 and CHARINDEX('PLQM',#test) < 0) and req.CreatedBy IS null)
)

Related

MySQL Multiple Case When Exists Statement

I have two tables. Let's call it: SEATS and SEAT_ALLOCATION_RULE table.
Below are the table schema:
CREATE TABLE IF NOT EXISTS `SEATS` (
`SeatID` int(11) NOT NULL AUTO_INCREMENT,
`SeatName` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`SeatID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
INSERT INTO `SEATS` (`SeatID`, `SeatName`) VALUES
(1, 'Super VIP'),
(2, 'VIP'),
(3, 'Business'),
(4, 'Economy'),
(5, 'Standing');
CREATE TABLE IF NOT EXISTS `SEAT_ALLOCATION_RULE` (
`SeatID` int(11) NOT NULL DEFAULT '0',
`Origin` varchar(50) NOT NULL DEFAULT '0',
`Destination` varchar(50) NOT NULL DEFAULT '',
`Passenger_Type` varchar(25) NOT NULL DEFAULT '',
PRIMARY KEY (`SeatID`,`Origin`,`Destination`,`Passenger_Type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `SEAT_ALLOCATION_RULE` (`SeatID`, `Origin`, `Destination, `Passenger_Type`) VALUES
(1, 'Malaysia','',''),
(2, 'Malaysia','Singapore',''),
(3, 'Malaysia','Singapore','Senior_Citizen'),
(4, 'Bangkok','Japan','Student'),
(5, 'Cambodia','China','Senior_Citizen');
SEAT_ALLOCATION_RULE table determines which seat should a passenger be assigned to based on the following order in priority:
1. Origin, destination, and passenger_type match
2. Origin and destination match
3. Origin match
It means that if all the fields (origin, destination, and passenger_type) match, it should take higher priority than if it is just two fields match and so on. If a column is empty, it is considered as unspecified and hence has lower priority. So, for example:
If the Origin is Malaysia, Destination is Singapore, and Passenger_Type is Senior_Citizen, it should return seatID 3
If the Origin is Malaysia, Destination is Singapore, and Passenger_Type is Student, it should return seatID 2 (since it only match Origin and Destination)
If the Origin is Malaysia, Destination is US, and Passenger_Type is Student, it should return seatID 1 (since it only match Origin).
Now, based on the rules above, if the origin is Malaysia, destination is Singapore, and Passenger_Type is student, the query to return seatID is as follow:
SELECT s.SeatID, s.SeatName
FROM SEATS s
WHERE
CASE WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = 'Singapore'
AND r.Passenger_Type='Student') Then 1
WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = 'Singapore'
AND r.Passenger_Type='') Then 1
WHEN EXISTS(
select 1
from SEAT_ALLOCATION_RULE r
where s.SeatID = r.SeatID
AND r.Origin = 'Malaysia'
AND r.Destination = ''
AND r.Passenger_Type='') Then 1 END
However, the query above does not work as it will return seatID 1 and 2, but the expected output is only seatID 2 (since origin and destination matches and it takes higher precedence). Can someone help to correct my SQL query?
This should do the trick:
select seatid
from seat_allocation_rule sar
order by ((sar.origin = :origin) << 2) + ((sar.destination = :destination) << 1) + (sar.passenger_type = :passenger_type) desc,
((sar.origin <> '') << 2) + ((sar.destination <> '') << 1) + (sar.passenger_type <> '') asc
limit 1
To understand how:
create table testcase (
origin varchar(255),
destination varchar(255),
passenger_type varchar(255),
expected_seat int(11)
);
insert into testcase values ('Malaysia','Singapore','Senior_Citizen',3),
('Malaysia','Singapore','Student',2),
('Malaysia','US','Student',1);
select * from (
select tc.*,
sar.seatid,
case when sar.seatid = tc.expected_seat then 'Y' else '-' end as pass,
((sar.origin = tc.origin) << 2)
+ ((sar.destination = tc.destination) << 1)
+ ((sar.passenger_type = tc.passenger_type) << 0) as score,
((sar.origin <> '') << 2)
+ ((sar.destination <> '') << 1)
+ ((sar.passenger_type <> '') << 0) as priority
from seat_allocation_rule sar
cross join testcase tc
) x order by expected_seat desc, score desc, priority asc;
This fixes the existing SQL:
SELECT DISTINCT s.SeatID, s.SeatName
FROM SEATS s
LEFT JOIN SEAT_ALLOCATION_RULE r ON r.SeatID = s.SeatID
AND r.Origin = 'Malaysia'
AND (
(r.Destination = 'Singapore' AND r.Passenger_Type IN ('Student', ''))
OR
(r.Destination = '' AND r.Passenger_Type = '')
)
WHERE r.SeatID IS NOT NULL
But it's only a partial solution, and it's hand-coding logic you really want to apply based solely on the data.
A complete solution will use hypothetical inputs for your passenger's ticket info to produce all eligible seats. This is a great use of lateral joins/apply, which are sadly lacking in MySql (all of their major competitors have had these for at least two release cycles, along with other gems that are absent from the current MySql release like windowing functions, ctes, full joins... I could go on). Here's how I'd do it in Sql Server:
SELECT p.PassengerID, s.SeatID, s.SeatName
FROM Passenger p
CROSS APPLY (
SELECT TOP 1 r.SeatID
FROM SEAT_ALLOCATION_RULE r
WHERE COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
ORDER BY
CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END DESC
) r
INNER JOIN SEATS s ON s.SeatID = r.SeatID
WHERE p.PassengerID = /* passenger criteria here */
I know the Sql Server solution isn't much immediate help to you, but perhaps it will suggest a better MySql solution.
Without APPLY, the only way I know to do this is to first compute the MAX() match count for your passengers (how many parts of the rules match):
SELECT p.PassengerID,
MAX(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END) AS MatchCount
FROM Passenger p
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
GROUP BY p.PassengerID
And then use that to filter down to results that have the same number of matches:
SELECT p
FROM Passenger p
INNER JOIN ( /* matchecounts */
SELECT p.PassengerID,
MAX(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END) AS MatchCount
FROM Passenger p
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
GROUP BY p.PassengerID
) m ON m.PassengerID = p.PassengerID
INNER JOIN SEAT_ALLOCATION_RULE r ON COALESCE(NULLIF(r.Origin, ''),p.Origin) = p.Origin
AND COALESCE(NULLIF(r.Destination,''), p.Destination) = p.Destination
AND COALESCE(NULLIF(r.Passenger_Type,''),p.Passenger_Type) = p.Passenger_Type
INNER JOIN SEATS s ON s.SeatID = r.SeatID
WHERE m.MatchCount =
(CASE WHEN r.Origin <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Destination <> '' THEN 1 ELSE 0 END
+ CASE WHEN r.Passenger_Type <> '' THEN 1 ELSE 0 END)
AND p.PassengerID = /* Passenger criteria here */
Which repeats a lot of code as well as effort in the DB, and is not very efficient. You can repeat the passenger criteria in the nested query, but that would only help a little. This option might also return multiple records for a passenger if they match two rules equally, though you can solve this easily enough with a GROUP BY expression.
In either case, note you can improve performance and simplify code by using actual NULL values instead of empty strings for missing parts of the SEAT_ALLOCATION_RULE table.

Distinct in concatenated columns from a table in ms sql

I run this query in my db the results are not distinct. Is there any solution to get the distinct results while using concatenation in select clause.
select
case
when c.SubtypeId_FK is null then c.TypeDescription
else c.TypeDescription + ' In ' + cs.Subtype
end as Experties
from
CaseTLS c,
CaseLawyer cl ,
Lawyer l ,
CaseSubtype cs
where
c.CaseId = cl.CaseID
and cl.ComputerCode = l.ComputerCode
and l.ComputerCode = #p1
and (
c.SubtypeId_FK = cs.SubtypeId or c.SubtypeId_FK is null
)
Simply use Distinct in select clause.
Try this:
select
DISTINCT case
when c.SubtypeId_FK is null then c.TypeDescription
else c.TypeDescription + ' In ' + cs.Subtype
end as Experties
from
CaseTLS c,
CaseLawyer cl ,
Lawyer l ,
CaseSubtype cs
where
c.CaseId = cl.CaseID
and cl.ComputerCode = l.ComputerCode
and l.ComputerCode = #p1
and (
c.SubtypeId_FK = cs.SubtypeId or c.SubtypeId_FK is null
)

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 *

MySQL Compare Rows with empty entries

I've read a lot of the examples on self join, but they don't seem to cover the case where some fields are not in some rows.
For eg, I have a database with:
testId, testItem, testResult
And the rows:
1,test1,1
1,test2,0
1,test3,1
2,test1,0
2,test4,1
2,test5,1
I would like the output:
testItem,a.testId,b.testId,a.testResult,b.testResult
test1,1,2,1,0
test2,1,NULL,0,NULL
test3,1,NULL,1,NULL
test4,NULL,2,NULL,1
test5,NULL,2,NULL,1
Essentially, I want to compare each testItem (test1->test5) from two different testIds (1 and 2) and compare their testResult values, factoring in testIds that may not have the same test Items.
Given your exact requirement, you can try this:
select testItem
, max(case when testID = 1 then testID else null end) as testID1
, max(case when testID = 2 then testID else null end) as testID2
, max(case when testID = 1 then testResult else null end) as testResult1
, max(case when testID = 2 then testResult else null end) as testResult2
from mytable
where testID in (1,2)
group by testItem
This makes a lot of assumptions about your data, so take it with a grain of salt.
It looks like you want a FULL OUTER JOIN, which is not supported in MySQL. You can emulate this with a UNION of two queries: a LEFT JOIN query and RIGHT JOIN which throws out matching rows.
Something like this will return the specified resultset:
SELECT a.testItem
, a.testId AS `a.testId`
, b.testId AS `b.testId`
, a.testResult AS `a.testResult`
, b.testResult AS `b.testResult`
FROM mytable a
LEFT
JOIN mytable b
ON b.testItem = a.testItem
AND b.testId = 2
WHERE a.testId = 1
AND a.testItem IN ('test1','test2','test3','test4','test5')
UNION ALL
SELECT d.testItem
, c.testId
, d.testId
, c.testResult
, d.testResult
FROM mytable d
LEFT
JOIN mytable c
ON c.testItem = d.testItem
AND c.testId = 1
WHERE d.testId = 2
AND d.testItem IN ('test1','test2','test3','test4','test5')
AND c.testId IS NULL
ORDER
BY 1,2,4
(I included the predicates on testItem IN ('test1' thru 'test5') because you specified that as a requirement; those predicates could be removed if you want all values for testItem included.)
SQLFiddle Demo
select testItem,
group_concat(IFNULL(testId,'null') separator ', ') testIds,
group_concat(IFNULL(testResult, 'null') separator ', ') testResults
from table_name group by testItem;