SQL get to select multiple names from select subquery - sql

I am writing select statement in SQL Server. I have to add a select query.
select
acct.AccountID,
acct.Username,
acct.LastNm + ', ' + acct.FirstNm as Name ,
acct.Lastlogin,
acct.email as Email,
(select acct2.FirstNm + ' ' + acct2.LastNm as Name from tblUserAccount acct2
join tblReviewers ra2 on acct2.AccountID = ra2.ReviwerID) as Reviewers
from tblUserAccount acct
I need to get more names from a table called tblReviwers. So 1 user from the tblUserAccount table could be associated with multiple reviews.
The tblReviewers only has 3 column AnalystID, ReviewerID, and Date. When I select on the JOIN between TblUserAccount and TblReviewers on a test AccountID = AnalystID, I can get multiple ReviewerIDs, which their firstname and lastname are located in the tblUserAccount. This is the reason why I use a select subquery
When I run the query, I get the following error
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
I am trying to write a VIEW to get a data.
Any help is greatly appreciated.

A query for a column name can only contain a single record result set. If you have an entry with multiple results causes that error.
I think you are missing disclosure of a possible extra component needed in the reviewers table, the who entered it. This will result in a query similar to the following.
The aliases and relations will appear obvious, but need to be confirmed for your actual structure.
select
EnterBy.AccountID,
EnterBy.Username,
EnterBy.LastNm + ', ' + EnterBy.FirstNm as Name ,
EnterBy.Lastlogin,
EnterBy.email as Email,
ReviewBy.FirstNm + ' ' + ReviewBy.LastNm as ReviewerName
from
tblReviewers r
tblUserAccount EnterBy
on r.AccountID = EnterBy.AccountID
tblUserAccount ReviewBy
on r.ReviwerID = ReviewBy.AccountID
REVISION BASED ON ADDITIONAL DATA
Based on providing the analystID on who entered, you should be good with
select
EnterBy.AccountID,
EnterBy.Username,
EnterBy.LastNm + ', ' + EnterBy.FirstNm as Name ,
EnterBy.Lastlogin,
EnterBy.email as Email,
STUFF(( Select
', [' + ReviewBy.LastNm + ', ' + ReviewBy.FirstNm + '] ' AS [text()]
From
tblReviewers r
JOIN tblUserAccount ReviewBy
on r.ReviwerID = ReviewBy.AccountID
where
r.AnaylstID = EnterBy.AccountID
For XML PATH('')), 1, 2, '' ) as AllReviewers
from
tblUserAccount EnterBy

You cannot have a column that contains multiple rows in a single result set, it just doesn't make sense from SQL perspective. Hence the error.
You should JOIN the tblReviewers table instead of subselecting it. That will yield all Reviewers. Then, JOIN again on the tblUserAccount table to get the name of the Reviewer, and you are all set.
SELECT
acct.AccountID,
acct.Username,
acct.LastNm + ', ' + acct.FirstNm as Name ,
acct.Lastlogin,
acct.email as Email,
acct2.LastNm + ', ' + acct2.FirstNm as ReviewerName ,
FROM tblUserAccount acct
JOIN tblReviewers revi
ON on acct.AccountID = revi.ReviewerID
JOIN tblUserAccount acct2
ON on acct2.AccountID = revi.AnalystID

Starting from Sql Server 2017, You can use something like STRING_AGG function, which combines values from multiple rows into a single string.
Then, your Reviewers column in your query might look like this:
(select STRING_AGG(Name, ',') from
(select acct2.FirstNm + ' ' + acct2.LastNm as Name from tblUserAccount acct2
join tblReviewers ra2 on acct2.AccountID = ra2.ReviwerID
where ra2.AnalystID = acct.AccountID)
) as Reviewers
In this case, names(first name + last name) of the reviewers for the current user will be separated by commas.

Subselects in select lists can only be used to return one value.
In your case, use joins
SELECT
a.AccountID,
a.Username,
a.LastNm + ', ' + a.FirstNm as Name ,
a.Lastlogin,
a.email as Email,
b.LastNm + ', ' + b.FirstNm as ReviewerName
FROM
tblUserAccount a
LEFT JOIN tblReviewers r ON a.AccountID = r.AnalystID
INNER JOIN tblUserAccount b ON r.ReviewerID = b.AccountID
I also used a LEFT JOIN to the reviewers table, in case there is no reviewer defined for an analyst.
You will get several rows per analyst, if more than one reviewer is assigned to it. Usually I solve this problem in the front-end by making a report that puts the main data in a group header (the analyst) and the related date (the reviewers) in the detail section of the report.
Starting with SQL Server 2017, you can also use the STRING_AGG function to concatenate the values of string expressions.
SELECT
a.AccountID,
a.Username,
a.LastNm + ', ' + a.FirstNm AS Name ,
a.Lastlogin,
a.email AS Email,
STRING_AGG(
( SELECT b.LastNm + ' ' + b.FirstNm
FROM
tblReviewers
INNER JOIN tblUserAccount b ON r.ReviewerID = b.AccountID
WHERE
r.AnalystID = a.AccountID ),
', ') AS ReviewerName
FROM
tblUserAccount a
This allows you to return more than one reviewer in one field.

Related

Using the results of a SQL query as parameters for a second one

Our SQL developer put together the following query to basically pull a list of any employee who has logged into our system today. This query works perfectly and will spit out a list of names. What I need to do is take the list of names it spits out and then use those in a new query to change a column on a different table for each of those names.
select distinct(t.CC_FullName) as Employee,
t.CC_Supervisor as Supervisor,
t.StaffCimID
from (
select s.*,
r.CC_FullName,
r.CC_Supervisor,
r.StaffCimID
from (
select AgentFirstName + ' ' + AgentLastName as AgentName,
Agent
from pia.dbo.Five9IntraDayExtract with(nolock)
group by AgentFirstName + ' ' + AgentLastName,
Agent
) s
inner join pia.dbo.StaffInformationNew r with(nolock)
ON CASE
WHEN s.Agent LIKE '%_manual' AND s.Agent = r.Five9Name_MTM THEN 1
WHEN s.Agent NOT LIKE '%_manual' AND s.Agent = r.Five9Name THEN 1
ELSE 0
END = 1
and r.EndDate is null
) t
where t.CC_FullName is not null
and t.StaffCimID is not null
order by t.CC_FullName, t.CC_Supervisor
so basically after that runs I get a list with three columns. I need to take the name column and basically do the following:
Update Attendance Set Seated = '1' where name = 'John Doe'
I need to do that for every result from the initial query. What's the best way to do that?
Add that to the top of your query...
Update Attendance
Set Seated = '1'
where name in
(select t.CC_FullName from (
select s.*,
r.CC_FullName,
r.CC_Supervisor,
r.StaffCimID
from (
select AgentFirstName + ' ' + AgentLastName as AgentName,
Agent
from pia.dbo.Five9IntraDayExtract with(nolock)
group by AgentFirstName + ' ' + AgentLastName,
Agent
) s
inner join pia.dbo.StaffInformationNew r with(nolock)
ON CASE
WHEN s.Agent LIKE '%_manual' AND s.Agent = r.Five9Name_MTM THEN 1
WHEN s.Agent NOT LIKE '%_manual' AND s.Agent = r.Five9Name THEN 1
ELSE 0
END = 1
and r.EndDate is null
) t
where t.CC_FullName is not null
and t.StaffCimID is not null)

SSRS Subreport runs multiple times, I only want it running once

I have a report that has a drillthrough subreport that runs multiple times when it has more than one relationship to a many to many item that has nothing to do with the subreport.
Main report query
SELECT DISTINCT
cat.CategoryName AS 'Category Name', sub.SubCategoryName AS 'SubCategory Name', cur.Status, cur.PastConsiderationFlag, cur.Model, cur.Version, cur.Vendor, cur.AvailableDate AS 'Available Date', cur.EndOfProduction AS 'End of Production',
cur.EndOfSupport AS 'End of Support', dep.DepartmentName AS 'Department Name', emp.FirstName + ' ' + emp.LastName AS 'Tech Owner', emp2.FirstName + ' ' + emp2.LastName AS 'Tech Contact',
cur.NumOfDevices AS '# of Devices', cur.UpgradeDuration AS 'Upgrade Duration', cur.FiscalConsideration AS 'Fiscal Consideration', cur.Description, cur.SupportingComments, cur.CurrencyId, STUFF
((SELECT ', ' + pl.PlatformName AS Expr1
FROM Platform AS pl LEFT OUTER JOIN
Currency_Platform AS cp ON cur.CurrencyId = cp.CurrencyId
WHERE (pl.PlatformId = cp.PlatformId) FOR XML PATH('')), 1, 1, '') AS 'Platforms', ISNULL(STUFF
((SELECT ', ' + cu2.Model AS Expr1
FROM Currency AS cu2 RIGHT OUTER JOIN
Currency_Dependency AS cd ON cur.CurrencyId = cd.CurrencyId
WHERE (cu2.CurrencyId = cd.DependencyId) FOR XML PATH('')), 1, 1, ''), 'N/A') AS 'Dependencies', ISNULL(STUFF
((SELECT ', ' + cu2.Model AS Expr1
FROM Currency AS cu2 RIGHT OUTER JOIN
Currency_Affected AS ca ON cur.CurrencyId = ca.CurrencyId
WHERE (cu2.CurrencyId = ca.AffectedId) FOR XML PATH('')), 1, 1, ''), 'N/A') AS 'Affected Apps', Currency_Platform.PlatformId
FROM Currency AS cur INNER JOIN
SubCategory AS sub ON cur.SubCategoryId = sub.SubCategoryId INNER JOIN
Category AS cat ON sub.CategoryId = cat.CategoryId LEFT OUTER JOIN
Employee AS emp ON cur.OwnerId = emp.EmployeeId LEFT OUTER JOIN
Employee AS emp2 ON cur.ContactId = emp2.EmployeeId LEFT OUTER JOIN
Department AS dep ON cur.PortfolioOwnerId = dep.DepartmentId LEFT OUTER JOIN
Currency_Platform ON cur.CurrencyId = Currency_Platform.CurrencyId
Even though it's a distinct select, the subreport will run equal to the amount of Platforms it belongs to. I'll include the Query for the subreport here.
;with cte as (
-- anchor elements: where curr.Status = 1 and not a dependent
select
CurrencyId
, Model
, Version
, ParentId = null
, ParentModel = convert(varchar(128),'')
, Root = curr.Model
, [Level] = convert(int,0)
, [ParentPath] = convert(varchar(512),Model + Version)
from dbo.Currency as curr
where curr.Status = 1
/* anchor's do not depend on any other currency */
and not exists (
select 1
from dbo.Currency_Dependency i
where curr.CurrencyId = i.DependencyId
)
-- recursion begins here
union all
select
CurrencyId = c.CurrencyId
, Model = c.Model
, Version = c.Version
, ParentId = p.CurrencyId
, ParentModel = convert(varchar(128),p.Model + p.Version)
, Root = p.Root
, [Level] = p.[Level] + 1
, [ParentPath] = convert(varchar(512),p.[ParentPath] + ' > ' + c.Model + ' ' + c.Version)
from dbo.Currency as c
inner join dbo.Currency_Dependency as dep
on c.CurrencyId = dep.DependencyId
inner join cte as p
on dep.CurrencyId = p.CurrencyId
)
select CurrencyId, ParentPath, Model + ' ' + Version AS 'Model' from cte
WHERE CurrencyId = #CurrencyId
When I run the subreport individually, everything is fine. When I open the subreport through the main report passing the CurrencyId as a parameter, it does so as many times as the amount of platforms it belongs to.
Is there a way I can correct this either by improving the queries, or as I would prefer, force the subreport to only run once no matter what?
Thanks so much for having a look.
You can use SQL Server Profiler to check the following things.
How many times and with what parameters is the subreport query has ran
How many values your first query returned
I don't think your problem is more about SSRS than it is about your T-SQL Code. I'm going to guess and say that the subreport object is in the report detail section of the report. That means that the subreport is going to render once for every row in the main queries dataset. I don't have any idea what your container report actually looks like but one option you have might be to include the subreport in the header or footer section and have it run off of a MAX(), MIN(), of a value that you know will be the same for every row.

SQL server Stuff on multiple columns

I want to concatenate the value of multiple columns for the same ID.
I managed to concatenate for the first column, but when trying the same syntax for the second I'm having an error "The multi-part identifier EnqAct.[ActionID] could not be bound."
Example_Data_Result
Here I managed to group several MachineName together, as seen in "Column1" but I can't manage to group both the MachineName and Description in their own column
My working Query :
SELECT Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
Stuff((SELECT ', ' + Mach.[MachineName]
FROM [dbo].[Machine] Mach
INNER JOIN [dbo].[MachineEnquiry] MachEnq
ON Mach.[MachineID] = MachEnq.[MachineID]
WHERE Enq.[EnquiryID] = MachEnq.[EnquiryID]
FOR XML PATH('')), 1, 2, ''),
DetAct.[Description]
FROM [dbo].[Enquiry] Enq
INNER JOIN [dbo].[EnquiryAction] EnqAct
ON EnqAct.[EnquiryID] = Enq.[EnquiryID]
INNER JOIN [dbo].[DetailsAction] DetAct
ON DetAct.[ActionID] = EnqAct.[ActionID]
INNER JOIN [dbo].[DetailsPriority] DetPrio
ON DetPrio.[PriorityID] = Enq.[Priority]
GROUP BY Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
DetAct.[Description]
My non working Query :
SELECT Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description],
Stuff((SELECT ', ' + Mach.[MachineName]
FROM [dbo].[Machine] Mach
INNER JOIN [dbo].[MachineEnquiry] MachEnq
ON Mach.[MachineID] = MachEnq.[MachineID]
WHERE Enq.[EnquiryID] = MachEnq.[EnquiryID]
FOR XML PATH('')), 1, 2, ''),
Stuff((SELECT ', ' + DetAct.[Description]
FROM [dbo].[DetailsAction] DetAct
INNER JOIN [dbo].[EnquiryAction] EnqAct
ON EnqAct.[ActionID] = DetAtc.[ActionID]
WHERE Enq.[EnquiryID] = EnqAct.[EnquiryID]
FOR XML PATH('')), 1, 2, '')
FROM [dbo].[Enquiry] Enq
INNER JOIN [dbo].[DetailsPriority] DetPrio
ON DetPrio.[PriorityID] = Enq.[Priority]
GROUP BY Enq.[EnquiryID],
Enq.[CustomerName],
DetPrio.[Description]
Both work the same way, I have a table Enquiry which will have an EnquiryID.
then in my table EnquiryAction or MachineEnquiry I will have entitys with an EnquiryID and an Action/Machine ID
Then in my DetailsAction/Machine Table I will have the Action/Machine ID, and the string I want to get and concatenate.
Why am I having an error and is it possible to achieve what I'm trying to do ?

SQL show the max of count

I am using SQL server 2014. I have two tables Member and MemberPosition. The MemberPostion table records a history of each member in the database. The memberID is the primary key in the member table, and is a foreign key in the MemberPosition table. I need to return the member that has held the most positions.
Here is the query I am using:
Select
M.MemberFName + ' ' + M.MemberLName as Name
from Member M
Join MemberPosition MP
ON MP.MemberID = M.MemberID
Group By M.MemberFName + ' ' + M.MemberLName
Having Count(MP.MemberID) = (Select max(P) from
(Select Count(MP.MemberID) as P From MP))
I am getting an error near the last )
It tells me incorrect syntax near 'End of file'. Expecting AS,ID, or QUOTED_ID.
Can you tell me what I am doing wrong. I have tried following other examples from the forums but I cannot figure this out.
Subqueries in the from clause need an alias. In your case, this is buried deep in the having clause:
Select M.MemberFName + ' ' + M.MemberLName as Name
from Member M Join
MemberPosition MP
ON MP.MemberID = M.MemberID
Group By M.MemberFName + ' ' + M.MemberLName
Having Count(MP.MemberID) = (Select max(P)
from (Select Count(MP.MemberID) as P
From MP
) p
------------------------------------^
);
There are other ways to do what you want but this follows your query.
Here is an alternative:
Select TOP 1 WITH TIES M.MemberFName + ' ' + M.MemberLName as Name
from Member M Join
MemberPosition MP
ON MP.MemberID = M.MemberID
Group By M.MemberFName + ' ' + M.MemberLName
ORDER BY COUNT(*) DESC;

How do I display different values as different columns in SQL?

I have a table with columns UserID, SiteID, SiteViews and another with UserID, First, Last
And I need to display the data as First + Last, Site1Views, Site2Views
There are only 2 site IDs and I need to have the sum of the SiteViews per User.
Currently I have:
select s.UserFirstName + ' ' + s.UserLastName as 'Name',
j1.SiteViews as 'Site1Name',
j2.SiteViews as 'Site2Name'
from (Users s INNER JOIN Usage j on s.UserID = j.UserID)
I don't know how to do this. Any help would be appreciated.
Sounds like you might want to use PIVOT for this? I can't test it, but this should get you going int he right direction?
select s.UserFirstName + ' ' + s.UserLastName as Name,
[Site1Name],
[Site2Name]
FROM
(SELECT s.UserFirstName + ' ' + s.UserLastName,
SiteName,
SiteVisits
from Users s
INNER JOIN Usage j1
on s.UserID = j1.UserID
)
PIVOT (SUM(SiteVisits) FOR SiteName IN ([Site1Name],[Site2Name])) as p
how I understood it
select s.UserFirstName + ' ' + s.UserLastName as Name
,(Select COUNT(*) from SiteViews s1 where s.UserID = s1.UserID /*other condition*/) as SiteView1
,(Select COUNT(*) from SiteViews s2 where s.UserID = s2.UserID /*other condition*/) as SiteView2
from Users s