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.
I have added a new column to a table and want to prepopulate it.
At the moment I have this:
update Table_A
set packages = 'a:1:{i:0;a:2:{s:4:"name"; s:' + ltrim(str(len(p.name))) + ':"' + p.name + '";'+
's:11:"category_id"; a:1:{i:0;s:1:"0";}}}'
from broker_product as Table_A
join scheme s on Table_A.scheme_id = s.id
join product p on p.id = s.product_ids
where Table_A.packages is null
What I want to do is populate category_id with a value based on the values of a column in product, as opposed to the fixed string that it is now.
An example of what is in product.risks is:
a:2:{i:0;a:5:{s:10:"field_name";s:24:"Gadget Accidental Damage";s:19:"risk_category_value";s:4:"1.00";s:13:"variable_name";s:24:"gadget-accidental-damage";s:11:"description";s:0:"";s:10:"hover_text";s:0:"";}i:1;a:5:{s:10:"field_name";s:32:"Home Emergency Accidental Damage";s:19:"risk_category_value";s:4:"2.00";s:13:"variable_name";s:0:"";s:11:"description";s:0:"";s:10:"hover_text";s:0:"";}}
In this example I would like category_id to be:
a:2:{i:0;s:1:"0";i:1;s:1:"1";}
which is an array of the same length as products.risk, with the values i:0;s:1:"0"; for the size of the array, counting the number of elements in product.risks.
As an example, I am looking for something like this (with correct regex, not the broken stuff I've supplied):
update Table_A
set packages = 'a:1:{i:0;a:2:{s:4:"name"; s:' + ltrim(str(len(p.name))) + ':"' + p.name + '";'
's:11:"category_id"; ' + preg_replace('/a:(\d+):{(i:\d+;)/', 'a:$1:{$2s:1:"0";}', p.risks) + '}}'
from broker_product as Table_A
join scheme s on Table_A.scheme_id = s.id
join product p on p.id = s.product_ids
where Table_A.packages is null
I want to do this query using active record so I can make the query safe from injection. DB is Postgresql. Ruby on Rails 3.2.11
def find_possible_duplicates(last_name, date_of_birth, organisation_id)
find_by_sql( 'select c.* from clients c' +
' join locations l on c.location_id = l.id' +
" where c.last_name ILIKE #{last_name}" +
" and c.date_of_birth = #{date_of_birth}" +
" and l.organisation_id = #{organisation_id}"
end
Any help appreciated
Following is the Active Record query :
Client.select('clients.*').
joins('join locations on clients.location_id=locations.id').
where('last_name like ? and date_of_birth =? and organisation_id = ?',last_name,date_of_birth,organisation_id)
I have a SQL Query :
SELECT * FROM Customer c
LEFT JOIN Invoice I ON I.InvcNum = C.Cust_InvcNum
some thing changed and the join does not work because there is no consistency in the data in the 'Cust_InvcNum'. So now when it does not find the record for the join or if it is null it needs to check for another condition.
LEFT JOIN Invoice I ON I.InvcNum = (SELECT p.InvcPrefix FROM Prefix WHERE p.DealerID = I.DealrID ) + '-' + I.InvcNum
second join I do works but it is taking too long for it get me data. Is there any other way to do this.
Earlier it used to be
Join on I.InvcNum = C.Cust_InvcNum
both the columns has the same data like DlrCd-InvcNum i.e both the columns 1234-A789
but not it could match on the above data or now the column 'InvcNum' in invoice table
can be populated like Dlrd-InvcNum or InvcPrefix-InvcNum
So InvcNum = 1234-A789 but CustNum = I94-A789
so we need to check if the for InvoicePrefix-InvcNum
SELECT *
FROM Customer c
LEFT JOIN (
SELECT i.InvcNum, p.InvcPrefix + '-' + I.InvcNum AS pInvcNum
FROM Invoice i LEFT JOIN Prefix p ON i.DealrID = p.DealrID
) ip ON c.Cust_InvcNum = CASE WHEN c.Cust_InvcNum = ip.InvcNum
THEN ip.InvcNum
ELSE ip.pInvcNum END
I apologize that my SQL Kung Fu isn't up to par, but this seems like a basic task that I can't seem to complete.
I've got two tables in Sql Server 2008
tblBoxAddress
--Address
--Zip
--Latitude
--Longitude
tblUpdatedDated
--Address
--latitude
--longitude
I have to update the latitude and longitude of tblBoxAddress with the lat. and long. from tblUpdatedData by matching on the address. The problem is that tblUpdatedData.Address contains the zip code. In tblBoxAddress, this is broken into two separate columns.
I've been able to make a select statement work correctly
select * from tblUpdatedData t
inner join (
Select Address + ' ' + zip As 'full_address', Latitude, Longitude from tblBoxAddress) d
on d.full_address = t.Address
However, I can't figure out how to combine the address and zip of tblBoxAddress on an update statement. This was as far as I've gotten:
update d
set d.Latitude = t.latitude, d.Longitude = t.longitude
FROM tblBoxAddress d inner join
tblUpdatedData t on t.Address = d.Address + ' ' + d.zip as 'full_address'
Any help is appreciated.
You don't need to alias in the update clause(s). e.g. try:
update d
set d.Latitude = t.latitude, d.Longitude = t.longitude
FROM tblBoxAddress d inner join
tblUpdatedData t on t.Address = d.Address + ' ' + d.zip;