SQL Server : get IN value for which it was found that row - sql

I'm having difficulties for solving this problem. I'm using Microsoft SQL Server 2014 (ver. 12.0.4100.1).
I have two tables contacts and business. I have an array of contact usernames. I'm fetching a business list from this username array with a subquery in the WHERE, like this:
SELECT business.id, business.name, business.notes
FROM business
WHERE business.id IN (SELECT contacts.business_id
FROM contacts
WHERE contacts.username IN ('username1', 'username2', 'username3'))
This query is working correctly, but I can't figure out how to select also the value for which every row was found; for example: if I fetch the business from the contact with username 'username1', I want to fetch it and see the result:
business.id = 1
business.name = 'Business 1'
business.notes = 'Notes from business 1.'
contacts.username = 'username1'
Getting that result, I could see easily from what contact came every business.
Thank you in advance!
EDIT: There may be more than one contact for every business, so doing an INNER JOIN would return duplicated business results for every contact. I want to know exactly what contact was the one which was selected on the subquery.

I think you are looking for a join:
SELECT b.id, b.name, b.notes, c.username
FROM business b JOIN
contacts c
ON b.id = c.business_id
WHERE c.username IN ('username1', 'username2', 'username3');

Related

Retrieve the most recent person record added to an account

I am trying to build a table of Contact IDs (Primary Keys) of the most recently created records assigned to each Account of a certain type in our Salesforce org.
Working in Salesforce Marketing Cloud, I'm trying to build a sample list that I can setup to update automatically so the records I'm testing against are never stale. I only need one example from each account to do my testing. Since I want to make sure the record isn't stale, I want to select the most recent record assigned to each Account.
Every Contact is assigned to one and only one Account. The Account ID lives as a foreign key on the Contact Record. The created date of the Contact is also a field on the Contact record.
The Sample list needs to contain the email address, ContactID, and the name of the Management Company, which lives on the Account record.
I figured doing a directional JOIN toward the Account table would do the trick, but that didn't work. I figure that's because there's nothing distinguishing which record to pick.
This is what I've got for code, which is pretty useless...
SELECT
C.Email AS Email,
C.Id AS Id18,
C.AccountID AS AccountID,
A.Management_Company AS ManagementCompany
FROM
ENT.Contact_Salesforce_DE AS C
RIGHT JOIN ENT.Account_Salesforce_DE AS A ON C.AccountID = A.Id
WHERE
A.RecordTypeId = '1234567890ABCDEFGH' AND
A.Management_Company IS NOT NULL AND
C.Email IS NOT NULL
The syntax checks out, but I get a system error every time I run it.
Marketing Cloud runs on an older version of SQL Server, so some more recent query functions won't always work.
And yes, I'm a relative noob to SQL. Won't surprise me if this has a really simple solution, but I couldn't find another entry describing the solution, so...
If I followed you correctly, you want to pull out the latest contact associated with each account.
On database servers that do not support window function (which seems to be the case of your RDBMS), one typical solution is to add a special condition to the JOIN. This NOT EXISTS condition uses a subquery to ensure that the record being picked in the child table is the most recent one (in other words : there is no child record with a highest creation date than the one being joined) :
SELECT
c.Email AS Email,
c.Id AS Id18,
c.AccountID AS AccountID
FROM
ENT.Account_Salesforce_DE AS a
INNER JOIN ENT.Contact_Salesforce_DE AS c
ON c.AccountID = a.Id
AND c.email IS NOT NULL
AND NOT EXISTS (
SELECT 1
FROM ENT.Contact_Salesforce_DE AS c1
WHERE
c1.email IS NOT NULL
AND c1.AccountID = a.Id
AND c1.CreatedDate > c.CreatedDate
)
WHERE
A.RecordTypeId = '1234567890ABCDEFGH'
AND A.Management_Company IS NOT NULL

Scalar subquery contains more than one row

Im working with H2 database and wanted to move some data. For that I created the following Query:
UPDATE CUSTOMER
SET EMAIL = SELECT service.EMAIL
FROM CUSTOMER_SERVICE AS service
INNER JOIN CUSTOMER AS customer ON service.ID = customer.CUSTOMER_SERVICE_ID;
When I now perform it in the H2 console I get the following error:
Scalar subquery contains more than one row; SQL statement:
UPDATE CUSTOMER
SET EMAIL = SELECT service.EMAIL
FROM CUSTOMER_SERVICE AS service
INNER JOIN CUSTOMER AS customer ON service.ID = customer.CUSTOMER_SERVICE_ID [90053-192] 90053/90053 (Hilfe)
What is this error telling me?
EDIT
What I want to achiev with my query:
Actually every CUSTOMER has a CUSTOMER_SERVICE. And I simply want to move the COLUMN EMAIL from CUSTOMER_SERVICE to the CUSTOMER Table. for that I already added a email column to the user. I hoped to be able to do it with my query but obviously not.
Your query is not syntactically valid (all subqueries must have parentheses around them).
What you are missing is a correlation clause. I believe you want:
UPDATE CUSTOMER c
SET EMAIL = (SELECT cs.EMAIL
FROM CUSTOMER_SERVICE s
WHERE s.ID = c.CUSTOMER_SERVICE_ID
);
I don't know what this is supposed to be: [90053-192] 90053/90053 (Hilfe).
Your select query is returning more than one row. If you don't want it to, then you need to do something like an aggregate or LIMIT 1 or something similar.
Your sub-query for at least one of your customers has multiple email addresses.
You could ... (Select top 1 serverice.email ...
Or ... (Select max(serverice.email) ...
Update Customer Set EMail=B.Email
From Customer A
Join (Select ID,max(EMail) as EMail From CUSTOMER_SERVICE Group By ID) B
on (A.CUSTOMER_SERVICE_ID = B.ID)
I've spend a lot time with this error type (there shoudn't be duplicates in DB).
At last I've found problem via SQL with COUNT like this:
UPDATE CUSTOMER
SET EMAIL = SELECT COUNT(service.EMAIL)
FROM CUSTOMER_SERVICE AS service
INNER JOIN CUSTOMER AS customer ON service.ID =
customer.CUSTOMER_SERVICE_ID;
And then select problem rows with EMAIL!='1'

SQL Gather Data from the same column with possible different results

The problem I am currently experiencing is that if the Contact.email are different then it displays both as NULL. If I use OR instead of AND it acquires both of the emails but in different rows, so they are duplicated.
I think that I need to assign the alias but I'm not sure how to do that.
SELECT Item.brought, Contact.email AS SalesContact, Contact.email AS TechContact
FROM Customer
LEFT JOIN Contact
ON Item.sales_id = Contact_id
AND Item.tech_id = Contact_id;
What I am trying to do is associate the Item.brought with the two possible email address which as stored in a different table.
Any advice would be greatly predicated.
Many thanks.
You are reading the same email. You need to join twice to Contact, like this:
SELECT Item.brought, SC.email AS SalesContact, TC.email AS TechContact
FROM Customer
LEFT JOIN Contact SC
ON Item.sales_id = SC.Contact_id
LEFT JOIN Contact TC
ON Item.tech_id = TC.Contact_id;
Explanation: You need two Contact records, which are not necessarily the same, since you can imagine a tech who is not also on sales and a sales who is not also a tech. So you are joining the sales guy using Item.sales_id and the tech guy using Item.tech_id.

How do I get all the institutions in my SQL query in oracle with inner join?

I'm trying to write a query in oracle SQL, first I am trying to edit a profile, so I want to change the institution that the user previously select it, but for that I must get all the institutions from a table named institution (id_institution, name_institution),
select user.user_name, institution.name_institution from user
inner join institution_has_user on user.id_user = institution_has_user.user_id_user
inner join institution on institution_has_user.institution_id_institution = institution.id_institution
where user = 'george';
But all I get It is the data that he register, and I want all the institutions, so I can fill a select html, just for editing purposes
If you want to return all the institutions from your above query, then you'll need to use an OUTER JOIN and move your WHERE criteria to your JOIN. This will however return NULL records for the user name field where there aren't any matches which might not be what you're looking for:
select distinct user.user_name, institution.name_institution
from institution
left join institution_has_user on institution_has_user.institution_id_institution = institution.id_institution
left join user on user.id_user = institution_has_user.user_id_user
and user.user_name = 'george';
Perhaps an easier alternative solution, just run two queries -- it should be perfectly fine to create a drop down list from a single select statement:
select name_institution
from institution

Help with Complex SQL Query

I'm still a neophyte when it comes to SQL queries, so I was hoping someone could lend me a hand.
Assume I have 3 tables, Skill, Set, and Contact, and 2 linking tables, SkillSet and ContactSet. (the 3 tables have an "ID" column that is being used as a primary key)
Contacts can have any number of sets, and vice versa (many-to-many)
Sets can have any number of skills, and vice versa (also many-to-many)
What I want is, when presented with a skill's ID, to return every contact with a set containing that skill.
Still with me?
Here's what I've got so far:
SELECT Set.ID as expr1
FROM SkillSet
WHERE Skill.ID = #SkillID
//this selects every set containing the Skill.
SELECT Contact.ID
FROM ContactSet
WHERE SET.ID = ?
//this is where I run into problems. I want to use the records returned from
//the previous SELECT query (expr1) but I'm unsure how.
//Would it be expr1.ID or expr1.Set.ID?
Thank you.
this should work just fine or at least lead you to the final solution, you only need the one query:
declare #skillid int
set #skillid = 1
SELECT C.*
FROM contact c
inner join SetContact SC on (sc.contactId = C.contactId)
inner join SkillSet SS on (ss.SetId = SC.SetId)
WHERE (SS.SkillId = #SkillId)