How to use ISNULL() function along with join - sql

While using the ISNULL function along with aliases of column name that I have given to form a left join, I get an error.
The error is:
I am unable to understand what am I doing wrong. The data is stored in customers table:
The sql code that I am using is:
select ISNULL(c2.name,'N/A') as referredby , c1.name as name
from customers as c1
left outer join customers as c2 on c1.referredby = c2.id
order by referredby;

Don't use isnull()! The standard version is coalesce():
select coalesce(cref.name, 'N/A') as referredby_name, c.name as name
from customers c left outer join
customers cref
on c.referredby = cref.id
order by referredby_name;
I made a two other changes. First, the table aliases better describe the role of the tables. I also changed the column alias to referredby_name, so it doesn't match a column in a table. Neither of these are required; with them, I think the query reads more easily.

Related

Issues while creating a view using SQL Server Management Studio 2017

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

How do I count all items for one table in a multiple INNER JOIN SQL?

I am inner joining multiple tables based on matching primary and foreign keys. One of the fields requires an aggregate count function that I'm having trouble with.
SELECT qry_Facility.Name, tbl_FacilityDates.DateChecked, Count(tbl_ActionItems.ActionItemsNameID)
FROM (qry_Facility INNER JOIN tbl_FacilityDates ON qry_Facility.NameID = tbl_FacilityDates.DatesNameID) INNER JOIN tbl_ActionItems ON qry_Facility.NameID = tbl_ActionItems.ActionItemsNameID
WHERE ((tbl_FacilityDates.Type=)”Restaurants”);
The SQL above produces an error of "You tried to execute a query that does not include the specified expression 'Name' as part of an aggregate function."
If I remove the aggregate count function, the INNER JOIN table works except that the action items are listed individually instead of counted together.
,...tbl_ActionItems.ActionItemsNameID
I think the error is indicating me to use a GROUP BY clause, but I'm not sure how to apply it here.
Any help would be appreciated!
Try the following:
SELECT qry_Facility.Name,
tbl_FacilityDates.DateChecked,
Count(tbl_ActionItems.ActionItemsNameID)
FROM (qry_Facility
INNER JOIN tbl_FacilityDates
ON qry_Facility.NameID = tbl_FacilityDates.DatesNameID)
INNER JOIN tbl_ActionItems
ON qry_Facility.NameID = tbl_ActionItems.ActionItemsNameID
WHERE ((tbl_FacilityDates.Type=)”Restaurants”)
Group by qry_Facility.Name,
tbl_FacilityDates.DateChecked

Can I do a left join without returning the conditional columns?

New to SQL but I want to be able to optimize my query by bringing just the right amount of data. I am doing a left join on CS Rep Name and WE, which are two columns present in both tables. I find that if I don't bring in CS Rep Name and WE in the TECDR table, the query would error. Is there a workaround to this? Since it is a left join, I don't need redundant data.
SELECT *
FROM Tish_Email_CSAT_Dump AS TECD
LEFT JOIN (SELECT CS_Rep_Name,
Team_Leader,
Operations_Manager,
Tenure,
WE,
FileName
FROM Tish_Email_CSAT_Dump_Roster) AS TECDR
ON TECD.CS_Rep_Name = TECDR.CS_Rep_Name
AND TECD.WE = TECDR.WE
When you embed a SELECT inside a query in place of a table, the result of a select (projection) behave like a table visible only inside the query.
In your case, the join is the same as if there were a table called TECDR with the columns that you select. Hence, if you leave out some columns of Tish_Email_CSAT_Dump_Roster from your SELECT, these columns would not be available for joining or selection.
However, in your case this is unnecessary: all you need to do is joining to the underlying table, like this:
SELECT
TECD.*
, TECDR.Team_Leader
, TECDR.Operations_Manager
, TECDR.Tenure
, TECDR.FileName
FROM Tish_Email_CSAT_Dump AS TECD
LEFT JOIN Tish_Email_CSAT_Dump_Roster AS TECDR
ON TECD.CS_Rep_Name = TECDR.CS_Rep_Name AND TECD.WE = TECDR.WE
select
<place the columns you want here>
from
Tish_Email_CSAT_Dump as TECD
Left join Tish_Email_CSAT_Dump_Roster as TECDR
On TECD.CS_Rep_Name = TECDR.CS_Rep_Name and TECD.WE = TECDR.WE
Hope the following helps or else please share the query that errors:
select TECD.Column1, TECD.Column2, TECDR.Column1, TECDR.Column2
from Tish_Email_CSAT_Dump as TECD
Left join Tish_Email_CSAT_Dump_Roster as TECDR
On TECD.CS_Rep_Name = TECDR.CS_Rep_Name and TECD.WE = TECDR.WE

Why we should specify column name in where clause at inner join when have same column name?

I have the query
select gltree.*,tsacc.confirm,tsacc.acc_no,commacc.* from tsacc
inner join commacc on tsacc.acc_no = commacc.acc_no and tsacc.glcode = commacc.glcode
inner join gltree on tsacc.glcode = gltree.glcode
where gltree.glcode = 12738
in this query two specified tables have 'glcode' column name , so
why I should specify table name in where clause eg. gltree.glcode and can't use only glcode without table name ? As we have just one glcode in executed query ?
You actually have threes columns with that name (tsacc.glcode, commacc.glcode and gltree.glcode), so you need to tell the database which one you mean.
The list of columns in the select list is evaluated as the last step when processing the statement. So when the DB processes the where clause it does not "know" which of them you are actually using (you could use all of them).
Plus: with an inner join it does indeed not matter, but if you were using an outer join it would make a big difference which of those three columns is used in the where clause.

Dynamic JOIN condition on a Table

I want to avoid string concatenation to create dynamic SQL query in SQL 2008.
How can I achieve the below functionality, if at all, efficiently ?
A table stores the various conditions a user had chosen to search DB by using one or more values to search tables from. For e.g. he can give SSN or DOB or both SSN and DOB.
So if he gives multiple values as input, then the query needs to find records matching ALL the criteria. This needs me to create queries from the below shown two tables
I always need to return personid, which may be from the person table, or the view.
Search conditions given by user will be stored in the 'conditions' table below
conditions
-------------
id,custid,dob,ssn,base
person
--------
id,firstname,ssn,dob
view
--------
id,personid,base
So, IF DOB is to be searched
SELECT p.personid from conditon c
INNER JOIN person p
ON p.dob=c.dob
WHERE c.condition=1
IF SSN and base is to be searched
SELECT v.personid from conditon c
INNER JOIN view v
ON c.base=v.base
INNER JOIN person p
ON p.ssn=c.ssn
WHERE c.condition=1
IF SSN,DOB and base is to be searched
SELECT v.personid from conditon c
INNER JOIN view v
ON c.base=v.base
INNER JOIN person p
ON p.ssn=c.ssn
AND
p.dob=c.dob
WHERE c.condition=1
Use the pattern below with IsNull() or Coalesce() function
Where ColumnName = IsNull(#InParameter, ColumnName)
or tyhe same pattern in a Join Condition
Join Table a
On [Other stuff]
And ColumnName = IsNull(#InParameter, ColumnName)
And then, if the parameter is supplied, the ql will filter or join based on the parameter value, if it not supplied or is null, the query will ignore it (ColumnValue = ColumnVale is always true (except for nullable columns)
EDITED: to add another predicate to Join Condition. because, in the case where you did not specifiy a parameter value, the join condition would always be true, and, unless some other predicate condition is in the join, you would effectively get a cartesian product...