How to reference the same column from 2 seperate IDs SQL Server - sql

I've been looking around for a bit unable to find an answer to this that works, So, I'm hoping someone can help me with my best bet to solve this. Basically I have a table with a User_id and a delegate_id, however both obviously reference the same user_mstr table. But what I want is the name of both the user and the delegate.
Here is the part of my query in question:
SELECT u.first_name, u.last_name, delegate_user_id, delegate_provider_ind,
tasks_ind, workflow_use_always_ind
FROM workflow_user_delegates ud
LEFT OUTER JOIN user_mstr u ON ud.user_id=u.user_id
But I want the delegate_id to be changed into a name, except obviously I already referenced user first and last name.
The exact software is SQL Server 2008. Thanks!

You can use alias = expression or expression AS alias to alias column names.
select
u.first_name
, u.last_name
, delegate_user_id
, delegate_first_name = d.first_name
, delegate_last_name = d.lastname
, delegate_provider_ind
, tasks_ind
, workflow_use_always_ind
from workflow_user_delegates ud
left join user_mstr u on ud.user_id = u.user_id
left join user_mstr d on ud.delegate_user_id = d.user_id

You need an additional LEFT JOIN:
SELECT u.first_name AS user_first_name, u.last_name AS user_last_name,
d.first_name AS delegate_first_name, d.last_name AS delegate_last_name,
delegate_user_id, delegate_provider_ind,
tasks_ind, workflow_use_always_ind
FROM workflow_user_delegates ud
LEFT OUTER JOIN user_mstr u ON ud.user_id=u.user_id
LEFT OUTER JOIN user_mstr d ON ud.delegate_user_id=d.user_id

You can join the same table twice, just provide different aliases for the table. Something like this:
....
FROM workflow_user_delegates ud
LEFT OUTER JOIN user_mstr u ON ud.user_id=u.user_id
LEFT OUTER JOIN user_mstr d ON ud.delegate_id=d.user_id
So any references to u.[...] in the SELECT will reference the one joined based on user_id, and any references to d.[...] will reference the one based on delegate_id.
To differentiate the columns in the SELECT clause, use a similar approach for aliasing. Something like this:
SELECT
....
u.first_name AS user_first_name,
u.last_name AS user_last_name,
d.first_name AS delegate_first_name,
d.last_name AS delegate_last_name,
....

Related

how can i access column from subquery

select u.phone, u.email , t.to_address (error from this)
from user_accounts u
where u.id
in
(select w.user_id
from wallets w
where w.id
in
(
select t.wallet_id
from withdraws t
where t.to_address
in
('1F6o1fZZ7', 'pJDtRRnyhDN')))
I want to get the column to_address from subquery. How can I get it in postgresql?
I try assign 'AS' for subquery but it didn't work
A join returns a result table constructed from data from multiple tables. You can also retrieve the same result table using a sub query. A sub query is simply a SELECT statement within another select statement.
select u.phone, u.email , t.to_address (
from user_accounts u
INNER JOIN wallets w ON u.id= w.user_id
INNER JOIN withdraws t ON t.wallet_id =w.id
where t.to_address in ('1F6o1fZZ7', 'pJDtRRnyhDN')
use join with all the table, you dont need any subquery
select u.phone, u.email , ww.to_address
from user_accounts u left join wallets w on u.id=w.user_id
left jon withdraws ww on w.id=ww.wallet_id
where ww.to_address in ('1F6o1fZZ7', 'pJDtRRnyhDN')
You can not access t.address because that column inside in condition.
I used left join but it seems it will be inner join type because you used filter in ('1F6o1fZZ7', 'pJDtRRnyhDN') though after applying where condition it also behave like inner join
You cannot achieve what you're trying using subquery. When you want records from different tables and they have a unique column in common that connects them then You should do it using a JOIN.
Sometimes (Not all cases) IN can cause performance problems, so you should consider knowing more about different types of JOINS(https://www.w3schools.com/sql/sql_join.asp)
Check the link for comparison:
Inner join versus doing a where in clause
About the Query:
SELECT
u.phone, u.email , t.to_address (error from this)
FROM
user_accounts u
INNER JOIN wallets w ON u.id = w.id
INNER JOIN withdraws t ON t.wallet_id = w.id
WHERE
t.to_address IN ('1F6o1fZZ7', 'pJDtRRnyhDN')

SQL convert "left join" with a "from" clause with multiple tables and a "where" condition

Image you have 2 tables like this:
User: with columns ID, NAME and APPARTMENT_ID.
Appartment: with columns ID, ADDRESS.
user.appartment_id is a foreign key for appartment.id.
With a left join I can do something like:
select u.name, a.address from user as u
left join appartment as a on u.appartment_id = a.id
And users with appartment_id null will match. If i write a select with this other structure (without using left join) those users won't match.
selct u.name, a.address from user as u, appartment as a
where u.appartment_id = a.id
Is there a way to modify the second query in order to obtain the same result set of the first, but without using left join?
Thanks
Without a left join you could just use this (assuming that the foreign key constraint has functioned correctly):
SELECT
u.name,
a.address
FROM user u
JOIN appartment a ON u.appartment_id = a.id
UNION
SELECT
name,
NULL AS address
FROM user
WHERE apartment_id IS NULL
;
But I'm curious as to why you'd want to do without a left join?
If you suspect that there there is incorrect data entered in user.apartment_id then you could use NOT EXISTS with a sub-query:
SELECT
u.name,
a.address
FROM user u
JOIN appartment a ON u.appartment_id = a.id
UNION
SELECT
name,
NULL AS address
FROM user
WHERE
NOT EXISTS (
SELECT 1
FROM appartment
WHERE appartment.id
= user.appartment_id)
);
This should cover you for null values and incorrect values.
If you are using Oracle, this is the old syntax for outer joins. You just need to add a (+) on the columns of the second table:
select u.name, a.address
from user as u, appartment as a
where u.appartment_id = a.id (+)
You will find this type of syntax a lot on Oracle environments, I guess that's why you asked it. You should probably use the new syntax though
Using left join is better, but here is an alternative.
select u.name, a.address
from user as u left join appartment as a on u.appartment_id = a.id
union
select name, null address
from user apartment_id is null

How to transform a row to a column and add it to the result set

I have 5 different tables as shown in the pictures.
I can combine them using that query but i want to add book read log with using book names as column name into that table.
I show my tables in picture with different colors.
select dbo.Users.name+' '+dbo.Users.surname AS name_surname,
dbo.Student_Facebook_Data.likes,
dbo.Student_Facebook_Data.posts,
dbo.Student_Facebook_Data.comments,
dbo.Attendance.absence,dbo.Attendance.physical_presence,
dbo.Attendance.virtual_presence
from dbo.Users inner join dbo.Student_Facebook_Data on dbo.Users.id=dbo.Student_Facebook_Data.student_id
inner join dbo.Attendance on dbo.Users.id=dbo.Attendance.student_id
I tried that queries but these are doesn't solve my problem:
select dbo.Users.name+' '+dbo.Users.surname AS name_surname ,dbo.Student_Log.content_id
from dbo.Student_Log inner join
dbo.Users on dbo.Student_Log.student_id=dbo.Users.id
select distinct(material_name)
from dbo.Material_Detail inner join
dbo.Student_Log on dbo.Student_Log.content_id=convert(varchar,dbo.Material_Detail.id)
select distinct(material_name)
from dbo.Material_Detail inner join
dbo.Student_Log on dbo.Student_Log.content_id=convert(varchar,dbo.Material_Detail.id)
If your database is SQL Server 2005 or higher, you can definitely do it using the PIVOT operator. For clarity, I'm only showing how to display the count for books and using simplified table names:
select * from (
select u.name as 'user_name',
b.name as 'book_name',
l.id as 'reading'
from dbo.Users u
left join dbo.RealLog l on u.id = l.user_id
left join dbo.Books b on l.bid = b.id
) x
pivot (count(reading) for book_name in ([one],[two],[three],[four],[five])) as count
PIVOT Reference: http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

sql - How to have multiple select/from statements in one query

I'm trying to pull a report where each column is selecting from a specific table set. However, one of the columns needs to pull from a completely different table set and still be included in the same report. Of course, this doesn't work:
select u.first_name, ticket_work.time_spent
FROM tickets LEFT OUTER JOIN ticket_work ON ticket_work.ticket_id = tickets.id JOIN users u
(select count(tickets.id) FROM tickets JOIN users u)
where tickets.assigned_to = u.id
...
So just the part (select count(tickets.id) FROM tickets JOIN users u) needs to be selecting from the different table set but still be included in the report.
I'm a little confused by your question. Are you wanting to return the user, the count of tickets for that user, and the amount of time spent overall? If so, something like this should work:
select u.id, u.first_name,
SUM(tw.time_spent) summed_time_spent,
COUNT(DISTINCT t.id) count_tickets
FROM users u
LEFT JOIN tickets t
ON u.id = t.assigned_to
LEFT JOIN ticket_work tw
ON tw.ticket_id = t.id
GROUP BY u.id, u.first_name
Your questions is unclear, but just generally, it sounds like you're trying to join to a derived table (i.e., a query). In that case, do this:
SELECT...
FROM...
table_A A LEFT JOIN
(SELECT keyfield, valuefield FROM table_b WHERE ...) B
ON A.keyfield = B.keyfield
Does that make sense? To make a derived table, you put a query inside of parenthesis, give it an alias ('B' in this case), and then join it to your other tables as though it were a regular table.
Don't know about your table structure but you may use a sub query for such requirement
select u.first_name, ticket_work.time_spent,(select count(tickets.id) FROM tickets where ticket.id=ticket_work.ticket_id) as myCount
FROM tickets LEFT OUTER JOIN ticket_work ON ticket_work.ticket_id = tickets.id JOIN users u
where tickets.assigned_to = u.id

SQL: Matching multiple columns value

I have a database set up so that the username (username) and id (id) are stored in the members table.
I have another table that records reports and I record each column in the table (fid), who reported it (rid) and who they were reporting (id) which both match to the user's id in the members table.
How could I get a query to pull the username for both the rid and id?
My current query is
SELECT selfreport.fid, selfreport.rid,
selfreport.id, members.username as username
FROM members, selfreport
WHERE members.id = selfreport.id
ORDER BY fid
but this only gets the username for who they were reporting. How can I get it to pull the username for both?
You need to join to your members table twice. Try something like this:
SELECT selfreport.fid,
selfreport.rid,
selfreport.id,
COALESCE(WhoReported.username, 'Not Specified') AS WhoReportedUN,
COALESCE(ReportedTo.username, 'Not Specified') AS ReportedToUN
FROM selfreport
LEFT JOIN members WhoReported ON WhoReported.id = selfreport.id
LEFT JOIN members ReportedTo ON ReportedTo.id = selfreport.rid
ORDER BY fid
Do not use implicit SQL '89 joins they are an antipattern.
Use explicit join syntax instead.
SELECT s.fid, s.rid, s.id, m1.username as username, m2.username as rusername
FROM selfreport S
INNER JOIN members m1 ON (m1.id = s.id)
INNER JOIN members m2 ON (m2.id = s.rid)
ORDER BY s.fid
If id or rid is optional, use a left join.
SELECT
s.fid, s.rid, s.id
, COALESCE(m1.username, 'nobody') as username
, COALESCE(m2.username, 'nobody') as rusername
FROM selfreport S
LEFT JOIN members m1 ON (m1.id = s.id)
LEFT JOIN members m2 ON (m2.id = s.rid)
ORDER BY s.fid
You need to join members twice:
SELECT selfreport.fid,
selfreport.rid,
selfreport.id,
m1.username AS ReportToUsername,
m2.username AS ReporteeUsername
FROM selfreport
INNER JOIN members m1
ON m1.id = selfreport.id
INNER JOIN members m2
ON m2.id = selfreport.rid
ORDER BY fid
Since you were doing an implicit join in your original query, I believe INNER JOIN will suit you well. However, if it's possible to have null values in selfreport.id or selfreport.rid, you should use LEFT JOIN instead.