Related
In a totals row (location is row group, date is the column group), I'm not sure how to calculate a total based on the below expression that I've been using to calculate "overcapacity" daily totals. I'm trying to total up the daily overcap counts.
The below expression works fine when grouped under the "date" column grouping. So each day in the range picked by the user displays with an "overcapacity" count (if the visitscounts > 7, then the result is visitscounts - 7, otherwise it is 0).
But I'm not sure how to total up the resultant overcapacity counts (I can total up visitcounts fine). The issue is that it takes the FULL daily count and THEN applies the -7, instead of just summing all the previously calculated daily counts (if the daily account exceeds 7, then it subtracts 7 from the full daily count, to come up with an "overcapacity" count).
=IIF(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0)) > 7,
SUM(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0))-7),
0)
ADDITIONAL INFORMATION
Dataset Query:
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
ORDER BY L.Location, D.[date]
OverCap New Column Testing
Dataset Query with Added OverCap Column:
SELECT
x.Location
, x.[date]
, x.VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
FROM (
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
) x
ORDER BY x.Location, x.[date]
Full Report Layout with OverCap added
Grouped by Location (row) and [date] (column), with a totals row outside row group for combined location.
report layout
Current Resultset with OverCap Column
CurrentResultSet
NOTES:
Result for LOC3-4 is 129 (see CurrentResultSet) if I use:
OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
Result for LOC3-4 is 34 if I use:
OverCap = IIF(Location = 'LOC3' OR Location = 'LOC4', VisitsCount,0)
Result for LOC3-4 is 24 if I use:
OverCap = IIF((Location = 'LOC3' OR Location = 'LOC4') AND VisitsCount > 7, VisitsCount,0)
Expressions Used Successfully for GROUPED locations:
DailyVisitorCount (used for both DailyVisitorCount and TotalVisitorCount).
=Sum(Fields!VisitsCount.Value)
DailyOverCapacityCount (used for both DailyOverCapacityCount and TotalOverCapacityCount):
=SWITCH(
Fields!Location.Value = "LOC1" AND Fields!VisitsCount.Value > 24, SUM(Fields!VisitsCount.Value - 24),
Fields!Location.Value = "LOC2" AND Fields!VisitsCount.Value > 16, SUM(Fields!VisitsCount.Value - 16),
Fields!Location.Value = "LOC3" AND Fields!VisitsCount.Value > 7, SUM(Fields!VisitsCount.Value - 7),
Fields!Location.Value = "LOC4" AND Fields!VisitsCount.Value > 7, SUM(Fields!VisitsCount.Value - 7),
Fields!Location.Value = "LOC5" AND Fields!VisitsCount.Value > 11, SUM(Fields!VisitsCount.Value - 11),
True, 0)
Averages were calculated by using the above expressions but adding to the end:
/CountDistinct(Fields!date.Value)
Expressions Used for combined location (outside grouped location row)
DailyVisitorCount (used successfully for both DailyVisitorCount and TotalVisitorCount).
=IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4", Sum(Fields!VisitsCount.Value), 0)
TotalOverCapCount (used successfully with DAILY TotalOverCapCount, but not the Total TotalOverCapCount
=IIF(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0)) > 7,
SUM(SUM(IIF(Fields!Location.Value = "LOC3" OR Fields!Location.Value = "LOC4",Fields!VisitsCount.Value,0))-7),
0)
Expressions still needed:
Total TotalOverCapCount (adds up daily totals for the duration)
Average TotalOverCapCount (average of daily totals for the duration)
As the expression you are trying to sum requires two scoped expression parts, it's actually difficult to then sum these.
What you need to do is
=SUM(
SUM(Fields!.MyField.Value, "ColumnGroup")
, "RowGroup")
This is probably not possible in your scenario. I abandoned the approach quickly and just updated the dataset query to return the data I needed instead
So the dataset query looked like this (using you sample data)
DECLARE #t TABLE([Location] varchar(10), [Date] Date, [VisitsCount] int)
INSERT INTO #t VALUES
('LOC1', '2022-10-31', 18), ('LOC1', '2022-11-01', 19),
('LOC1', '2022-11-02', 19), ('LOC2', '2022-10-31', 34),
('LOC2', '2022-11-01', 30), ('LOC2', '2022-11-02', 35),
('LOC3', '2022-10-31', 8), ('LOC3', '2022-11-01', 8),
('LOC3', '2022-11-02', 8), ('LOC4', '2022-10-31', 5),
('LOC4', '2022-11-01', 5), ('LOC4', '2022-11-02', 7),
('LOC5', '2022-10-31', 11), ('LOC5', '2022-11-01', 11),
('LOC5', '2022-11-02', 11)
SELECT
[Location], [Date], VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
FROM #t
As you can see, I added an OverCap column. Now all we need to do is sum that in the report.
The report design looks like this..
and the final report looks like this...
Obviously you might need to adapt this to suit whatever grouping you have going but I think it's probably a much simpler approach.
Edit after update by OP
You can wrap your original query in a SELECT and then move the order clause of of the sub query. That should give you the same results.
SELECT
[Location], [Date], VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
FROM (
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
) x
ORDER BY [Location], [date]
If you want to just get LOC3+4 at the end of the table
Then you can do this in SQL. All I've done here is taken the existing query, dumped the results to a temp table , then returned the results plus an extra row that only contains LOC3 and LOC4 data.
Note: I added a GroupOrder column so you can sort on this in the report to make sure the combined row appears at the end.
SELECT
[Location], [Date], VisitsCount
, OverCap = IIF(VisitsCount-7 <0 ,0, VisitsCount-7)
INTO #t
FROM (
SELECT
L.Location
, D.[date]
, COUNT(DISTINCT CAST(V.VisitID AS VARCHAR(10))+V.Location+V.[Room-Bed]) AS VisitsCount
FROM dbo.DateTable(#StartDate, #EndDate) AS D
CROSS JOIN (
SELECT DISTINCT Location FROM dbo.vHIMOverFlowBedReport2)
AS L LEFT JOIN dbo.vHIMOverFlowBedReport2 AS V ON D.[date] BETWEEN
V.EffectiveDate AND ISNULL(V.ServiceEndDate, #EndDate) AND V.Location = L.Location
WHERE V.EffectiveDate IS NULL OR
(V.EffectiveDate <= #EndDate OR
V.ServiceEndDate >= #StartDate OR
V.ServiceEndDate IS NULL)
GROUP BY
L.Location
, D.[date]
) x
SELECT
GroupOrder = 1
, [Location], [Date], VisitsCount, OverCap
FROM #t
UNION ALL
SELECT
GroupOrder = 2
, [Location] = 'LOC3+4', MIN([Date]), SUM(VisitsCount), SUM(OverCap)
FROM #t
WHERE [Location] IN ('LOC3', 'LOC4')
GROUP BY YEAR([Date]), MONTH([Date])
I know that union can be done to combine two queries if they have same number and type of columns. But I've a condition where I've to combine two select statement with different tables and different columns though 1 table is common in both i.e. PatientAppointment. Here are the two statements:
select p.CDRId, p.Gender,p.MRN,p.DoB as DOB,pa.AppointmentDateTime,cn.Description,ehv.ProgramName,
cn.CreatedBy as CareTeamStaffMember,cn.Profile as Role,cn.Title as Credentials,
date_format(pa.AppointmentDateTime, '%Y-%m') BillingMonth,
((case when duration like '% hour%' then substring_index(duration, ' hour', 1) * 60 else 0 end) +
(case when duration like '%min%' then substring_index(substring_index(duration, ' min', 1), ' ', -1) + 0 else 0 end)) as minutes
from Patient p inner join EnrollmentHistoryView ehv on ehv.CDRId = p.CDRId
inner join ClinicalNote cn on cn.CDRId = p.CDRId
inner join PatientAppointment pa on pa.CDRId = p.CDRId
where p.CDRId='9493b505-03b9-46a0-b009-99b34f7a5d41'
and ehv.ProgramName!='N/A'
group by p.CDRId, p.Gender, p.MRN, p.Dob, pa.AppointmentDateTime,cn.Description,cn.CreatedBy,cn.Profile,cn.Title,pa.Duration,ehv.ProgramName
UNION
SELECT AppointmentDateTime,
duration,
minutes,
CASE WHEN #prev_month != BillingMonth
THEN total >= 20
WHEN #prev_total < 20
THEN 1
ELSE 0
END 99457Elig,
CASE WHEN #prev_month != BillingMonth
THEN total >= 40
WHEN #prev_total < 40
THEN 1
ELSE 0
END 99458Elig,
#prev_month := BillingMonth BillingMonth,
#prev_total := total total
FROM (select AppointmentDateTime,
duration,
#cur_dur := ((case when duration like '% hour%' then substring_index(duration, ' hour', 1) * 60 else 0 end) +
(case when duration like '%min%' then substring_index(substring_index(duration, ' min', 1), ' ', -1) + 0 else 0 end)) as minutes,
CASE WHEN #year_month = date_format(AppointmentDateTime, '%Y-%m')
THEN #cum_sum := #cum_sum + #cur_dur
ELSE #cum_sum := #cur_dur
END total,
#year_month := date_format(AppointmentDateTime, '%Y-%m') BillingMonth
from PatientAppointment, (SELECT #year_month:='', #cum_sum:=0, #cur_dur:=0) variables
ORDER BY AppointmentDateTime) subquery,
(SELECT #prev_month:=0, #prev_total:=0) variable
ORDER BY AppointmentDateTime
The query is too complex and I can't create the data set also. Please help me with the approach. Give me some suggestion at least. I'll try it myself.
Consider your first query as Query1 and second query as Query2, you can use simple join between these two.
As you said PatientAppointment table is common in both, use its primary key(CDRId) as joining between these two. So your query would look like.
SELECT *
FROM ( Query1 ) AS table1
INNER JOIN ( Query2) AS table2 ON table1.CDRId = table2.CDRId;
If we use case when created column in join condition... code runs. But is it correct? If it is how is this executed?
select *,
case when position('/' in pax_name)>0
then SUBSTR(pax_name, 1, position('/' in pax_name)- 1)
end as **lastname**,
CASE WHEN position('/' in pax_name)>0
THEN SUBSTR(pax_name, position('/' in pax_name) + 1, LENGTH(pax_name))
END as **firstname**
from o
inner join m
on o.record=m.record
and o.pax_first_name = **firstname**
and o.pax_last_name = **lastname**
The column aliases defined in the select are not available in most of the query at the same level of the select. In particular, they are not available for the where or from clauses.
You can accomplish this using having:
select *,
(case when position('/' in pax_name) > 0
then SUBSTR(pax_name, 1, position('/' in pax_name)- 1)
end) as lastname,
(case when position('/' in pax_name) >0
then substr(pax_name, position('/' in pax_name) + 1, length(pax_name))
end) as firstname
from o inner join
m
on o.record = m.record
having o.pax_first_name = firstname and
o.pax_last_name = lastname;
You can simplify the logic. I think you simply want:
select *,
(case when pax_name like '%'
then substring_index(pax_name, '/', 1)
end) as firstname,
(case when pax_name like '%'
then substring_index(pax_name, '/', -1)
end) as lastname
from o inner join
m
on o.record = m.record
having o.pax_first_name = firstname and
o.pax_last_name = lastname;
I would also recommend dispensing with the having, so:
select *,
(case when pax_name like '%'
then substring_index(pax_name, '/', 1)
end) as firstname,
(case when pax_name like '%'
then substring_index(pax_name, '/', -1)
end) as lastname
from o inner join
m
on o.record = m.record
m.pax_name = concat_ws('/', o.pax_first_name, o.pax_last_name);
use subquery
select o1.* from (
select *,
case when position('/' in pax_name)>0
then SUBSTR(pax_name, 1, position('/' in pax_name)- 1)
end as **lastname**,
CASE WHEN position('/' in pax_name)>0
THEN SUBSTR(pax_name, position('/' in pax_name) + 1, LENGTH(pax_name))
END as firstname
from o
) o1 inner join m
on o1.record=m.record
and o1.pax_first_name = firstname
and o1.pax_last_name =lastname
Not sure whether the actually query matters but, I have a MySQL Stored Procedure where I commented out the other parts of the proc except the following query...
INSERT INTO temp_attribution (`attribute_type`, `domain`, `id`, `name`, `score`, `rank`, `partner_match`, `person_match`, `sponsor_match`, `date_match`)
SELECT 'Campaign' AS attribute_type, domain, id, name, score, (#proc_counter := #proc_counter + 1) AS rank,
partner_match, person_match, sponsor_match, date_match
FROM (
SELECT m_c.domain, m_c.campaign_id AS id, m_c.name, m_c.client_id, m_c.sent_date,
proc_sponsors AS invoice_sponsor, bs.sponsor AS campaign_sponsor,
proc_email AS invoice_email, aes_decrypt(m_r.email, in_encrypt_key) as campaign_email,
if (m_c.client_id = proc_client_id COLLATE latin1_general_ci, 'Yes', 'No') AS partner_match,
if (aes_encrypt(proc_email, in_encrypt_key) = m_r.email, 'Exact Email', 'Email Domain') AS person_match,
if (LOCATE(CONVERT(bs.sponsor USING utf8mb4), proc_sponsors) > 0, 'Sponsor',
if (CONVERT(bs.vendor USING utf8mb4) = proc_vendor, 'Vendor', 'No') ) AS sponsor_match,
if (datediff(proc_invoice_date, m_c.sent_date) BETWEEN 0 AND 92, 'Within Three', 'Within Six') AS date_match,
(
if (m_c.client_id = proc_client_id COLLATE latin1_general_ci, 45, 10) + 30 +
if (LOCATE(CONVERT(bs.sponsor USING utf8mb4), proc_sponsors) > 0, 10,
if (CONVERT(bs.vendor USING utf8mb4) = proc_vendor, 5, 0) ) +
if (datediff(proc_invoice_date, m_c.sent_date) BETWEEN 0 AND 92, 15, 5)
) AS score
FROM campaign_table m_c
INNER JOIN recipient_table m_r ON m_c.domain = m_r.domain AND m_c.campaign_id = m_r.campaign_id
LEFT JOIN booking_sponsor bs ON m_c.domain = bs.domain AND m_c.campaign_id = bs.campaign_id
WHERE datediff(proc_invoice_date, m_c.sent_date) BETWEEN 0 AND 185
AND ( aes_encrypt(proc_email, in_encrypt_key) = m_r.email OR m_r.email_domain = proc_email_domain )
) T ORDER BY score DESC, sent_date DESC LIMIT 5;
The fields starting with 'proc_' are actually variables declared at the beginning of the procedure and this only takes 0.385 seconds to initialise whereas the entire proc takes 15 seconds.
On a separate query window, I copied the relevant query and substituted variables starting with 'proc_' to test speed and optimise, like so...
INSERT INTO temp_attribution (`attribute_type`, `domain`, `id`, `name`, `score`, `rank`, `partner_match`, `person_match`, `sponsor_match`, `date_match`)
SELECT 'Campaign' AS attribute_type, domain, id, name, score, (#proc_counter := #proc_counter + 1) AS rank,
partner_match, person_match, sponsor_match, date_match
FROM (
SELECT m_c.domain, m_c.campaign_id AS id, m_c.name, m_c.client_id, m_c.sent_date,
'VENDOR SPONSOR VALUE' AS invoice_sponsor, bs.sponsor AS campaign_sponsor,
'johnsmith#domain.com' AS invoice_email, aes_encrypt('johnsmith#domain.com', 'secret_key') as campaign_email,
if (m_c.client_id = m_c.client_id COLLATE latin1_general_ci, 'Yes', 'No') AS partner_match,
if (aes_encrypt('johnsmith#domain.com', 'secret_key'), 'Exact Email', 'Email Domain') AS person_match,
if (LOCATE(CONVERT(bs.sponsor USING utf8mb4), 'VENDOR SPONSOR VALUE') > 0, 'Sponsor',
if (CONVERT(bs.vendor USING utf8mb4) = 'VENDOR', 'Vendor', 'No') ) AS sponsor_match,
if (datediff('2016-10-14', m_c.sent_date) BETWEEN 0 AND 92, 'Within Three', 'Within Six') AS date_match,
(
if (m_c.client_id = m_c.client_id COLLATE latin1_general_ci, 45, 10) + 30 +
if (LOCATE(CONVERT(bs.sponsor USING utf8mb4), 'VENDOR SPONSOR VALUE') > 0, 10,
if (CONVERT(bs.vendor USING utf8mb4) = 'VENDOR', 5, 0) ) +
if (datediff('2016-10-14', m_c.sent_date) BETWEEN 0 AND 92, 15, 5)
) AS score
FROM campaign_table m_c
INNER JOIN recipient_table m_r ON m_c.domain = m_r.domain AND m_c.campaign_id = m_r.campaign_id
LEFT JOIN booking_sponsor bs ON m_c.domain = bs.domain AND m_c.campaign_id = bs.campaign_id
WHERE datediff('2016-10-14', m_c.sent_date) BETWEEN 0 AND 185
AND ( aes_encrypt('johnsmith#domain.com', 'secret_key') = m_r.email OR m_r.email_domain = 'domain.com' )
) T ORDER BY score DESC, sent_date DESC LIMIT 5;
Now, magically without doing anything else, the query runs within two seconds. How is that possible?
Figured it out. Some of the declared variable type was different compared to the column being compared, so I guess MySQL could not compare them in the most efficient way possible.
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)
)