getting properties from table fails if I join the same table twice - sql-server

I am trying to combine data from two tables but running into issues because of the odd way the contacts table is formatted. When I run my query it returns no results, Why cant I get both phone and email? If I try to get them separately it works perfectly.
I have a Users table:
id Name email
1 Bill abc#gmail.com
And a Contacts table:
id Name Data
1 phone 1234
1 email abc#gmail.com
My MSSQL query:
select co.Data as phone,
co2.Data as Email
from Users u
left join Contacts co on c.id=u.id
left join Contacts co2 on c2.id=u.id
where co.Name='email'
and co2.Name='phone' --if i dont add this emails and ebverything show up

You need to add more predicates to your join. I agree that the table is not a great architecture. It is an EAV style which is a pain to work with.
select c.Data as phone
, co2.Data as Email
from Users u
left join Contacts c on c.id = u.id
AND co.Name = 'email'
left join Contacts co2 on c2.id = u.id
AND and co2.Name='phone'

Your issue is not reproducible. I ran this script:
DECLARE #Users TABLE (
id tinyint
);
INSERT INTO #Users (id) VALUES (1);
DECLARE #Contacts TABLE (
id tinyint
, [Name] varchar(31)
, [Data] varchar(31)
);
INSERT INTO #Contacts (id, Name, Data) VALUES (1,'Phone','1234'),(1,'email','abc#gmail.com');
select co.Data as phone,
co2.Data as Email
from #Users u
left join #Contacts co on co.id=u.id
left join #Contacts co2 on co2.id=u.id
where co.Name='phone'
and co2.Name='email'
And got:
phone Email
1234 abc#gmail.com
So you had some typo or something else that you left of out your post causing your query not to work.
For instance, I corrected your aliases to use co and co2 throughout. There are places in your query where you used c and c2.
Also I corrected the where clause to associate co with "phone" and co2 with "email", since that's how they are associated in the SELECT list. You have them backwards in the query in your question.

You can create a view pivoting your contacts data which will make many other uses of your contacts data much simpler.
CREATE VIEW vContactsPivoted
AS
SELECT
id, email, phone
FROM
Contacts
PIVOT (MAX(data) FOR [name] IN (email, phone)) pivoted
After that you can use simple joins like any other traditional table:
SELECT
u.id,
u.[Name],
c.phone,
c.email
FROM
[Users] u
JOIN vContactsPivoted c ON u.id = p.id

Related

How to do sub-query correctly while selecting two tables in Oracle?

I need to do a sub-query from a table to find all employees working in the same department that is part of the same city, but I'm not getting it.
I have the following tables:
Table departments
DEPARTMENTS
department_id
department_name
location_id
Table locations
LOCATIONS
location_id
street_address
postal_code
city
state_province
country_id
Table employees
EMPLOYEES
employee_id
first_name
last_name
email
phone_number
hire_date
job_id
department_id
My code right now is something like that :
SELECT
firt_name,
department_id,
job_id
FROM employees
WHERE state_province = (SELECT state_province FROM locations
WHERE state_province = 'Sao Paulo');
The problem is that while I want to select state_province from the table locations, I can't select the name, department id and job id from the table employees. How can I select both tables while doing the sub-query ?
Anyway, sorry if I did something wrong in the code, I am new to sub-queries.
You could try doing a join between the two tables instead:
SELECT
e.firt_name,
e.department_id,
e.job_id,
l.* -- replace with columns you really want
FROM employees e
INNER JOIN locations l
ON e.state_province = l.state_province
WHERE
e.state_province = 'Sao Paulo';
I don't know which columns you want to select from locations, but it doesn't really make sense to do a join just for state_province alone, as the employees table already has this column. So I just included location.* as a placeholder which you can replace with the columns you actually want.
Edit:
A join is the way to go here IMO, but if you absolutely need to use a subquery, then you can move your current subquery from the WHERE clause to the SELECT clause:
SELECT
firt_name,
department_id,
job_id,
(SELECT l.state_province FROM locations l
WHERE e.state_province = l.state_province) state_province
FROM employees e;
Note that this will only work if there is one matching province. For this and performance reasons, my join query is probably what you would want to use in practice.
I think in your case, sub-query may not be necessary.
A join table can do the trick.
SELECT e.first_name, e.department_id, e.job_id, l.state_province
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
LEFT JOIN locations l ON d.location_id = l.location_id
WHERE l.state_province = 'Sao Paulo';

What kind of JOIN should I use to join these tables?

I have the following three tables that I am trying to join together and create an overview of all desktops and whoever has one assigned to their UserID if any.
dbo.Users
ID Name Lastname JobTitle
118 Ryan Doe Field Engineer
119 Jessica Braun Technical Consultant
120 Daniel Sous Web developer
121 Amy Amyson Intern
.. etc
dbo.LightDesktops
ID Model MACAddress UserID
1 HP1234 AA:AA:AA:AA:AA:AA 118
2 HP1234 BB:BB:BB:BB:BB:BB 121
3 HP1234 AA:BB:BB:AA:BB:AA NULL
4 HP1234 BB:AA:BB:AA:AA:BB 124
dbo.MediumDesktops
ID Model MACAddress UserID
1 HP12PRO AA:AB:AA:BB:AA:BA 132
2 HP12PRO BB:BA:AB:BA:BB:AA 119
3 HP12PRO AA:BA:BA:AB:AA:BA 123
4 HP12PRO BB:BB:BB:AB:BA:BB 241
I managed to figure out how to do it per type of desktop, for example LightDesktops:
SELECT * FROM LightDesktops LEFT OUTER JOIN Users ON LightDesktops.UserID = Users.UserID
That will show me a nice overview of the light desktops with their information as well as whoever has one assigned to if any.
If I'd like to have an overview of the light desktops that are not used and therefore in stock I can do
SELECT * FROM LightDesktops LEFT OUTER JOIN Users ON LightDesktops.UserID = Users.UserID WHERE LightDesktops.UserID IS NULL
How can I accomplish the same results, but for both tables containing information of our desktops? I tried to use an UNION but returned me lots of duplicate values.
Using UNION to bring the light and medium desktops tables together as a single dataset shouldn't give you duplicates unless the tables contain duplicate values in rows accross all columns in your SELECT clauses and you use UNION ALL. If you know your tables have unique values use UNION ALL to give a performance boost.
I would combine the two tables in a common table expression (cte) and then join the resultant table with a LEFT OUTER JOIN to your user table which can also be filtered to find entries where there is no match WHERE [user].[UserID] IS NULL, NB, that would return orphaned rows in your desktops tables where the user has been deleted; alternatively drop the left outer join and use WHERE [desktop].[UserID] IS NULL to return only dekstops without assiged users.
You could try the following code;
WITH cte_Desktop AS
(
SELECT
[ID] as [DesktopID],
'Light Desktop' as [DekstopType],
[Model],
[MACAddress],
[UserID]
FROM [dbo].[LightDesktops]
UNION
SELECT
[ID],
'Medium Desktop',
[Model],
[MACAddress],
[UserID]
FROM [dbo].[MediumDesktops]
)
SELECT
[desktop].*
FROM cte_Desktop AS [desktop]
LEFT OUTER JOIN [dbo].[Users] AS [user]
on [user].[UserID] = [desktop].[UserID]
WHERE [user].[UserID] IS NULL
Use Full join to get report of all users present. it will give you the full report. On top of this results Query for the userid is NULL
SELECT U.ID userid,
U.NAME,
LD.USERID LD_USERID,
LD.MODEL LIGHT_MODEL,
LD.MACADDRESS LIGHT_MAC,
LM.USERID LM_USERID,
LM.MODEL MEDIUM_MODEL,
LM.MACADDRESS MEDIUM_MAC
FROM #USERS U
FULL OUTER JOIN #LIGHTD LD
ON (U.ID = LD.USERID )
FULL OUTER JOIN #LIGHTM LM
ON (LM.USERID = U.ID)
While you can achieve what you need in a single query, it may be more supportable to break the table union out into a view which allows that logic to be reused across multiple queries and also allows for easier refactoring at a later date.
Nod to destination-data for reminding me of this.
View
CREATE VIEW [dbo].[Desktops] AS
(
SELECT
[ID] as [DesktopID],
'Light Desktop' as [DekstopType],
[Model],
[MACAddress],
[UserID]
FROM [dbo].[LightDesktops]
UNION
SELECT
[ID],
'Medium Desktop',
[Model],
[MACAddress],
[UserID]
FROM [dbo].[MediumDesktops]
)
Query
SELECT
[desktop].*
FROM [dbo].[Desktops] AS [desktop]
LEFT OUTER JOIN [dbo].[Users] AS [user]
on [user].[UserID] = [desktop].[UserID]
WHERE [user].[UserID] IS NULL
Try
WITH all as (
select model , userid from LightDesktops
union
select model , userid from MediumDesktops
)
select * FROM all where UserId IS NULL

TSQL Group By Issues

I have a TSQL query that I am trying to group data on. The table contains records of users and the access keys they hold such as site admin, moderator etc. The PK is on User and access key because a user can exist multiple times with different keys.
I am now trying to display a table of all users and in one column, all of the keys that user holds.
If bob had three separate records for his three separate access keys, result should only have One record for bob with all three of is access levels.
SELECT A.[FirstName],
A.[LastName],
A.[ntid],
A.[qid],
C.FirstName AS addedFirstName,
C.LastName AS addedLastName,
C.NTID AS addedNTID,
CONVERT(VARCHAR(100), p.TIMESTAMP, 101) AS timestamp,
(
SELECT k.accessKey,
k.keyDescription
FROM TFS_AdhocKeys AS k
WHERE p.accessKey = k.accessKey
FOR XML PATH ('key'), TYPE, ELEMENTS, ROOT ('keys')
)
FROM TFS_AdhocPermissions AS p
LEFT OUTER JOIN dbo.EmployeeTable as A
ON p.QID = A.QID
LEFT OUTER JOIN dbo.EmployeeTable AS C
ON p.addedBy = C.QID
GROUP BY a.qid
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');
END
I am trying to group the data by a.qid but its forcing me to group on every column in the select which will then not be unique so it will contain the duplicates.
Whats another approach to handle this?
Currently:
UserID | accessKey
123 | admin
123 | moderator
Desired:
UserID | accessKey
123 | admin
moderator
Recently, I was working on something and had a similar problem. Like your query, I had an inner 'for xml' with joins in the outer 'for xml'. It turned out it worked better if the joins were in the inner 'for xml'. The code is pasted below. I hope this helps.
Select
(Select Institution.Name, Institution.Id
, (Select Course.Courses_Id, Course.Expires, Course.Name
From
(Select Course.Courses_Id, Course.Expires, Courses.Name
From Institutions Course Course Join Courses On Course.Courses_Id = Courses.Id
Where Course.Institutions_Id = 31) As Course
For Xml Auto, Type, Elements) As Courses
From Institutions Institution
For Xml Auto, Elements, Root('Institutions') )
As I don't have the definitions for the other tables you have I just make a sample test data and you can follow this to answer yours.
Create statement
CREATE TABLE #test(UserId INT, AccessLevel VARCHAR(20))
Insert sample data
INSERT INTO #test VALUES(123, 'admin')
,(123, 'moderator')
,(123, 'registered')
,(124, 'moderator')
,(124, 'registered')
,(125, 'admin')
By using ROW_NUMBER() you can achieve what you need
;WITH C AS(
SELECT ROW_NUMBER() OVER(PARTITION BY UserId ORDER BY UserId) As Rn
,UserId
,AccessLevel
FROM #test
)
SELECT CASE Rn
WHEN 1 THEN UserId
ELSE NULL
END AS UserId
,AccessLevel
FROM C
Output
UserId AccessLevel
------ -----------
123 admin
NULL moderator
NULL registered
124 moderator
NULL registered
125 admin

SQL SELECT from SELECT

I am trying to build a single select statement from two separate ones.
Basically I have a list of Names in a table which do repeat like so:
Name| Date
John 2014-11-22
John 2013-02-03
Joe 2012-12-12
Jack 2011-11-11
Bob 2010-10-01
Bob 2013-12-22
I need to do a Select distinct Name from Records which returns John, Joe, Jack, Bob.
I then want to so a Select on another table where I pass in the rows returned above.
SELECT Address, Phone From dbo.Details
WHERE Name = {Values from first SELECT query}
Having trouble with the syntax.
If you do not want to return any values from the subquery, you can use either IN or EXISTS
SELECT Address, Phone From dbo.Details
WHERE Name IN (SELECT DISTINCT Name FROM Records)
-- OR --
SELECT Address, Phone From dbo.Details D
WHERE EXISTS (SELECT 1 FROM Records R WHERE R.Name = D.Name)
(In most RDBMS the EXISTS is less resource intensive).
If you want to return values from the subquery, you should use JOIN
SELECT
D.Address,
D.Phone,
R.Name -- For example
FROM
dbo.Details D
INNER JOIN dbo.Records R
ON D.Name = R.Name
SIDENOTE These are sample queries, it is possible that you have to fine tune them to match your exact requirements.
You can use:
SELECT Address, Phone, name
FROM details
-- "in" is the difference from your first query, needed due to multiple values being returned by the subquery
WHERE name in (
SELECT distinct name
FROM namesTable
)
Additionally the following should work:
SELECT d.Address, d.Phone, n.name
FROM details d
inner join (
select distinct name
from namesTable
) n on d.name = n.name
So there are two ways you can go about doing this. One, create a temporary table and perform a join (*actually in retrospect you could also join to your second table as a subquery, or use something like a CTE if you're using SQL SERVER, but the modifications if you wanted to go that route should be pretty obvious)
CREATE TEMPORARY TABLE my_table AS
{your first select query};
SELECT Address, Phone From dbo.Details
INNER JOIN my_table AS mt
ON mt.name = dbo.name
Another option would be to perform an IN or EXISTS query using your select query
SELECT Address, Phone From dbo.Details
WHERE name IN (SELECT name from my_table)
Or, better yet (eg SQL Server IN vs. EXISTS Performance),
SELECT Address, Phone From dbo.Details
WHERE EXISTS (SELECT * from my_table WHERE my_table.name = dbo.name)
You might have to modify the syntax slightly, depending on if you are using MySQL or SQL Server (not sure about that later, honestly). But this should get you started down the right path
This will give you the names and their address and phone number:
SELECT DISTINCT N.Name, D.Address, D.Phone
FROM dbo.Details D INNER JOIN dbo.Names N ON D.Name = N.Name
When using a subquery that is not scalar (doesn't return only one value) in the where clause use IN and of course only one column in the subquery:
SELECT Address, Phone
From dbo.Details
WHERE Name IN (Select Name from Table)

Need help creating a query for a non-normalized database

I've never worked with a non-normalized database before, so I'll try and explain my problem as best I can. So I have two tables:
The customers table holds all the customers information, and the orders table holds all the orders that they have placed. I haven't listed all the fields in the tables, just the ones that I need. The customer number in both tables is not the primary key, but I'm inner joining on them anyway. So the problem I'm having is that I don't know how to make a query that:
Selects all the customers with their first name, last name, and email, and also show the most recent orderdate, most recent total, and most recent ordertype. I know that I have to use a max() aggregate for the date, but that's as far as I got. Please help a noob out.
You can try:
SELECT FirstName,
LastName,
Email,
OrderDate,
OrderTotal,
OrderType
FROM Customers AS C
INNER JOIN Order AS O
ON O.CustomerNumber = C.CustomerNumber AND
O.OrderDate = (
SELECT MAX (O1.OrderDate)
FROM Order AS O1
WHERE O1.CustomerNumber = C.CustomerNumber)
)
assuming that Orders.OrderDate is unique for each CustomerNumber, does this work for you? if a single CustomerNumber has more than one entry in Order for OrderDate, you'll get each of those rows.
select c.FirstName, c.LastName, c.Email, o.OrderDate, o.OrderTotal, o.OrderType
from Customers c
join
(select CusomterNumber, max(OrderDate) as MostRecentOrderDate
from Orders
group by CustomerNumber
) mro on mro.CustomerNumber=s.CustomerNumber
join Orders o on o.OrderDate=mro.MostRecentOrdeDate and
o.CustomerNumber=mro.CustomerNumber
Try this:
SELECT
Customers.*, Orders.*
FROM
Customers
JOIN
(SELECT
Customer_Number,
MAX(Order_Date) OrderDate
FROM
Orders
GROUP BY
Customer_Number
) as Ord ON Customers.Customer_Number = Ord.Customer_Number
JOIN Order ON Orders.Customer_Number = Ord.Customer_Number
If you are doing this with SQL Server use the query designer and basically all you want to do is do a join since you have two keys that are the same one in Customer Table ->Customer Join on Order->Customer alias the Customer table as C and Orders table as O
so for example
SELECT Customer.*, Orders.*
From Customer c, Orders O INNER JOIN O where C.Customer Number = O.Customer Number
This should be enough to get you started.. if you don't want all the fields then fully qualify the names for example
SELECT C.FirstName, C.LastName, O.OrderDate, O.OrderType FROM Customer C, Orders O
WHERE C.Customer NUmber = O.Customer Number //this is another way of doing a Join when working with the where Clause.

Resources