Issues while creating a view using SQL Server Management Studio 2017 - sql

Create a view vw_contacttypedetails for
a. ContactTypeId, Name from person.contacttype
b. BusinessEntityId, PersonId from person.businessentitycontact
c. Join both the tables, resulting in the final display of 4 columns (2 from each table as mentioned)
d. THEN, run a query to see the data in vw_contacttypedetails
I attempted but got an invalid object name. Below is my query:
create view vwcontacttypedetails
as
select ContactTypeID,Name,BusinessEntityID,PersonID
from tblContacttype
join tblbusinessentitycontact
on Contacttype.ContactTypeID = businessentitycontact.ContactTypeID

It seems your join statement is wrong...
create view vwcontacttypedetails
as
select c.ContactTypeID,b.Name,b.BusinessEntityID,b.PersonID
from tblContacttype c
join tblbusinessentitycontact b
on c.ContactTypeID = b.ContactTypeID
For how the syntax of joins works, have a look here:
https://www.w3schools.com/sql/sql_join.asp
And from the official Microsoft documentation:
https://learn.microsoft.com/en-us/sql/relational-databases/performance/joins?view=sql-server-2017
Specifying the join conditions in the FROM clause helps separate them from any other search conditions that may be specified in a WHERE clause, and is the recommended method for specifying joins. A simplified ISO FROM clause join syntax is:
FROM first_table join_type second_table [ON (join_condition)]
join_type specifies what kind of join is performed: an inner, outer, or cross join. join_condition defines the predicate to be evaluated for each pair of joined rows. The following is an example of a FROM clause join specification:
FROM Purchasing.ProductVendor JOIN Purchasing.Vendor
ON (ProductVendor.BusinessEntityID = Vendor.BusinessEntityID)
The following is a simple SELECT statement using this join:
SELECT ProductID, Purchasing.Vendor.BusinessEntityID, Name
FROM Purchasing.ProductVendor JOIN Purchasing.Vendor
ON (Purchasing.ProductVendor.BusinessEntityID = Purchasing.Vendor.BusinessEntityID)
WHERE StandardPrice > $10
AND Name LIKE N'F%'
GO
And for your next question have a look here:
https://stackoverflow.com/help/how-to-ask

Related

where clause conditions in SQL

Below is a join based on where clause:
SELECT a.* FROM TEST_TABLE1 a,TEST_TABLE2 b,TEST_TABLE3 c
WHERE a.COL11 = b.COL11
AND b.COL12 = c.COL12
AND a.COL3 = c.COL13;
I have been learning SQL from online resources and trying to convert it with joins
Two issues:
The original query is confusing. The outer joins (with the (+) suffix) are made irrelevant by the last where condition. Because of that condition, the query should only return records where there is an actual matching c record. So the original query is the same as if there were no such (+) suffixes.
Your query joins TEST_TABLE3 twice, while the first query only joins it once, and there are two conditions that determine how it is joined there. You should not split those conditions over two separate joins.
BTW, it is surprising that the SQL Fiddle site does not show an error, as it makes no sense to use the same alias twice. See for example how MySQL returns the error with the same query on dbfiddle (on all available versions of MySQL):
Not unique table/alias: 'C'
So to get the same result using the standard join notation, all joins should be inner joins:
SELECT *
FROM TEST_TABLE1 A
INNER JOIN TEST_TABLE2 B
ON A.COL11 = B.COL11
INNER JOIN TEST_TABLE3 C
ON A.COL11 = B.COL11
AND B.COL12 = C.COL12;
#tricot correctly pointed out that it's strange to have 2 aliases with the same name and not getting an error. Also, to answer your question :
In the first query, we are firstly performing cross join between all the 3 tables by specifying all the table names. After that, we are filtering the rows using the condition specified in the WHERE clause on output that we got after performing cross join.
In second query, you need to join test_table3 only once. Since now you have all the required aliases A,B,C as in the first query so you can specify 2 conditions after the last join as below:
SELECT A.* FROM TEST_TABLE1 A
LEFT JOIN TEST_TABLE2 B
ON A.COL11 = B.COL11
left join TEST_TABLE3 C
on B.COL12 =C.COL12 AND A.COL3 = C.COL13;

SQL SELECT Statement Using Three Tables

I am trying to write a SQL Select statement to port some data from a Sybase environment to a MongoDB environment and I'm just trying to figure out the correct syntax to involve three different tables.
Basically what I need to do is do an INNER JOIN on two tables, and then do a matching check against a 3rd table. The three table names are "ar_notes", "customer_service_xref" and "service_notes_details"
This is what I tried:
SELECT * FROM ar_notes arn
LEFT JOIN customer_service_xref csx ON arn.customer_service_xref_id = csx.id_number
WHERE arn.visit_date = service_notes_details.date_of_visit
This doesn't work. I get a correlation error.
What should the syntax look like when involving three tables like this?
You said you need an INNER JOIN among three tables but your query does a LEFT JOIN between two and tries another join in the WHERE clause without refering that table in the FROM clause.
To just fix your query:
SELECT *
FROM service_notes_details snd, ar_notes arn
INNER JOIN customer_service_xref csx ON arn.customer_service_xref_id = csx.id_number
WHERE arn.visit_date = snd.date_of_visit
This is what you should use in current SQL syntax:
SELECT *
FROM ar_notes arn
INNER JOIN customer_service_xref csx ON arn.customer_service_xref_id = csx.id_number
INNER JOIN service_notes_details ON arn.visit_date = service_notes_details.date_of_visit
To be clear, this will only return lines in ar_notes that have corresponding values in customer_service_xref (joining by customer_service_xref_id) and in service_notes_details(joining by visit_date). Your original query, using LEFT JOIN would return lines from ar_notes even if there was no matching customer_service_xref_id.

When to cross or join two tables?

Example 1:
SELECT name
FROM Customer, Order
WHERE Customer.id = Order.cid
Example 2:
SELECT name
FROM Customer JOIN Order
ON Customer.id = Order.cid
What is the difference between these two queries? When should I cross two tables vs JOIN?
Both will give you identical result. So there is no real situation to use one over another.
The comma separated join, is an ANSI 89 standard join, INNER JOIN is the newer ANSI 92 standard join.
However comma separated join syntax is depreciated we always prefer to use INNER JOIN syntax. When you want to join more than one table it will be difficult to follow the join conditions in Where clause where as INNER JOIN syntax is more readable
CROSS JOIN operation is a Cartesian product. Result of CROSS JOIN operation
between set A and set B is the superset that contains all values.
Then with operator WHERE you are filtering this result set.
INNER JOIN operation will try to find rows from both tables that correspond predicate
after keyword ON. That rows will go to the result set.
Practically, SQL engine can choose its own physical implementation CROSS JOIN operator.
SQL engine doesn't have to get huge result set and then filter it. SQL engine behaviour will
be similar when using INNER JOIN operation.

Converting SQL query to Hive query

I am having some trouble converting my SQL queries into Hive queries.
Relational schema:
Suppliers(sid, sname, address)
Parts(pid, pname, color)
Catalog(sid, pid, cost)
Query 1: Find the pnames of parts for which there is some supplier.
I have attempted one of the query conversions for query 1 and I think it is correct If someone can let me know if it is correct or incorrect I would really appreciate it. They seem to be the same to me based on the info I have looked up for Hive.
Query 1: SQL
SELECT pname
FROM Parts, Catalog
WHERE Parts.pid = Catalog.pid
Query 1: Converted to Hive
SELECT pname
FROM Parts, Catalog
WHERE Parts.pid = Catalog.pid;
Query 2: Find the sids of suppliers who supply only red parts.
For the second query I am having trouble. Mainly I am having trouble with the "not exists" part and the defining what color we want part. Can someone help me figure this out? I need to put the SQL into a Hive query.
Query 2: SQL
SELECT DISTINCT C.sid
FROM Catalog C
WHERE NOT EXISTS ( SELECT *
FROM Parts P
WHERE P.pid = C.pid AND P.color <> ‘Red’)
If someone can help me get these into the correct Hive format I would really appreciate it.
Thank you.
Although I have never used HiveQL in looking up some of its documentation it appears to support outer joins written in plain sql. In that case this should work: (an outer join where there is no match)
select distinct c.id
from catalog c
left outer join parts p
on (c.pid = p.pid
and p.color <> 'Red')
where p.pid is null
Edit -- enclosed on clause in () , this is not normally required of any major databases but seems to be needed in hiveql -- (https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Joins).
Regarding your first query I don't think it wouldn't work in hive based on example queries in those docs however as another commenter mentioned it is best practice to use explicit joins via the join clause rather than implicit joins in the where clause. Think of the where clause as where you filter based on various conditions (except for join conditions), and the join clause as where you put all join conditions. It helps organize your query's logic. In addition, you can only imply inner joins (in the where clause). The join clause is needed any time you want to work with outer joins (as in the case of your second query, above).
This is the same as your first query but with explicit join syntax:
select pname
from parts p
join catalog c
on (p.pid = c.pid)

Group by in SQL Server giving wrong count

I have a query which works, goes like this:
Select
count(InsuranceOrderLine.AntallPotensiale) as potensiale,
COUNT(InsuranceOrderLine.AntallSolgt) as Solgt,
InsuranceProduct.Name,
InsuranceProductCategory.Name as Kategori
From
InsuranceOrderLine, InsuranceProduct, InsuranceProductCategory
where
InsuranceOrderLine.FKInsuranceProductId = InsuranceProduct.InsuranceProductID
and InsuranceProduct.FKInsuranceProductCategory = InsuranceProductCategory.InsuranceProductCategoryID
Group by
InsuranceProduct.name, InsuranceProductCategory.Name
This query over returns what I need, but when I try to add more table (InsuranceOrder) to be able to get the regardingUser column, then all the count values are way high.
Select
count(InsuranceOrderLine.AntallPotensiale) as Potensiale,
COUNT(InsuranceOrderLine.AntallSolgt) as Solgt,
InsuranceProduct.Name,
InsuranceProductCategory.Name as Kategori,
RegardingUser
From
InsuranceOrderLine, InsuranceProduct, InsuranceProductCategory, InsuranceSalesLead
where
InsuranceOrderLine.FKInsuranceProductId = InsuranceProduct.InsuranceProductID
and InsuranceProduct.FKInsuranceProductCategory = InsuranceProductCategory.InsuranceProductCategoryID
Group by
InsuranceProduct.name, InsuranceProductCategory.Name,RegardingUser
Thanks in advance
You're adding one more table to your FROM statement, but you don't specify any JOIN condition for that table - so your previous result set will do a FULL OUTER JOIN (cartesian product) with your new table! Of course you'll get duplication of data....
That's one of the reasons that I'm recommending never to use that old, legacy style JOIN - do not simply list a comma-separated bunch of tables in your FROM statement.
Always use the new ANSI standard JOIN syntax with INNER JOIN, LEFT OUTER JOIN and so on:
SELECT
count(iol.AntallPotensiale) as Potensiale,
COUNT(iol.AntallSolgt) as Solgt,
ip.Name,
ipc.Name as Kategori,
isl.RegardingUser
FROM
dbo.InsuranceOrderLine iol
INNER JOIN
dbo.InsuranceProduct ip ON iol.FKInsuranceProductId = ip.InsuranceProductID
INNER JOIN
dbo.InsuranceProductCategory ipc ON ip.FKInsuranceProductCategory = ipc.InsuranceProductCategoryID
INNER JOIN
dbo.InsuranceSalesLead isl ON ???????? -- JOIN condition missing here !!
When you do this, you first of all see right away that you're missing a JOIN condition here - how is this new table InsuranceSalesLead linked to any of the other tables already used in this SQL statement??
And secondly, your intent is much clearer, since the JOIN conditions linking the tables are where they belong - right with the JOIN - and don't clutter up your WHERE clauses ...
It looks like you added the table join which slightly multiplies count of rows - make sure, that you properly joining the table. And be careful with aggregate functions over several joined tables - joins very often lead to duplicates