I am working on Transact-SQL, Microsoft Azure.
I am trying to understand why in some join queries WHERE and AND both can be used and give the same result (or at least it seemed like the same result in my data base) and in other queries where doesn't work and and does.
Here, I am joining 2 tables:
select c.customerID, ca.addressID, ca.addressType
from salesLT.customer as c
join salesLT.customerADdress as ca
on c.customerID = ca.customerID
WHERE ca.addressType = 'Main Office'; --WHERE or AND works the same
This gives me what I was looking for = only the rows from customerAddress table where the type is 'Main Office'. Changing the word WHERE to AND gives the exact same result.
Now, the query is based on the previous, but I am trying to join 3 tables. Here the WHERE doesn't work and I have to put an AND:
select c.customerId, c.companyName, ca.addressID, ca.addressType, a.addressLine1, a. city
from salesLT.customer as c
join salesLT.customerAddress as ca
on c.customerID = ca.customerID
WHERE ca.addressType = 'Main Office' -- error: incorrect syntax near 'join'
join salesLT.address as a
on ca.addressId = a.addressID;
If I change the WHERE to AND it works. Why? What is the difference between the join of 2 tables and 3?
Thanks
If I change the WHERE to AND it works. Why?
Because using and is adding the condition to the on clause, but using where is a new clause.
Here is the full explanation: The basic syntax of a select statement when using multiple joins is:
SELECT <columns>
FROM <table 1>
JOIN <table 2> ON <condition>
JOIN <table 3> ON <condition>
WHERE <condition>
This means your second query should look like this:
select c.customerId, c.companyName, ca.addressID, ca.addressType, a.addressLine1, a.city
from salesLT.customer as c
join salesLT.customerAddress as ca on c.customerID = ca.customerID
join salesLT.address as a on ca.addressId = a.addressID
WHERE ca.addressType = 'Main Office';
If you will go to the link, you will see that a select statement syntax can get much more complicated - but for now, that basic syntax should be enough to get you started.
The second JOIN should be before the WHERE clause
select c.customerId, c.companyName, ca.addressID, ca.addressType, a.addressLine1, a. city
from salesLT.customer as c
join salesLT.customerAddress as ca
on c.customerID = ca.customerID
join salesLT.address as a
on ca.addressId = a.addressID
WHERE ca.addressType = 'Main Office'
;
Related
I am new to this and haven't been able to find the proper syntax for my table join...
SELECT
DISTINCT on (date (billing.starttime))
medias.name,
date (billing.starttime),
Count(distinct (billing.starttime)) as "# Plays",
Count(distinct(billing.playerid)) as "# Stores"
FROM
public.billing,
public.medias
JOIN ????? on billing.mediaitemid = medias.id
WHERE
medias.name LIKE any (array['COMM_7032%']) and
billing.starttime >= date('2017-04-26') and
billing.starttime < date('2017-05-01')
GROUP BY
date (billing.starttime),
medias.name
ORDER BY
date (billing.starttime)
I am not sure what fits where the ????? are. Everything that I have tried states that the relationship does not exist.
It should go:
...
FROM
public.billing JOIN public.medias on billing.mediaitemid = medias.id
WHERE
...
the syntax is
[table1] join [table2] on [condition]
from
public.billing b
inner join
public.medias m on b.mediaitemid = m.id
I am trying to wrap my head around sub-queries (correlated). Although the book explains (MS SQL Server 2012) it I'm still a little confused. Using three tables, Orders, Products and OrderDetails I want to find the sum of all products that were shipped to USA. I came up with the following query but do not quite understand how I got there except the correlation is referencing the 'where' in the outer query. Can someone correct my work and offer better explanation than book?
SELECT p.productid, p.productname, SUM(qty * od.unitprice) AS TotalAmount
FROM Production.Products AS p
JOIN Sales.OrderDetails AS od
ON p.productid = od.productid
WHERE N'USA' IN
(SELECT o.shipcountry
FROM Sales.Orders AS o
JOIN Sales.OrderDetails AS od
ON o.orderid = od.orderid
WHERE shipcountry = N'USA')
GROUP BY p.productid, p.productname;
SELECT
p.ProductID
, p.ProductName
, SUM(qty * od.UnitPrice) as [Total_Amount]
FROM
Production.Products productid
JOIN Sales.OrderDetails as od on p.productid = od.product
JOIN SalesOrders as o on o.OrderID = od.OrderID
WHERE
o.Shipcountry in ('USA')
Group BY
p.ProductID,
P.ProductName
The following should work - you technically dont require the sub query. Will only bog down the query.
here`s my query
SELECT cont.FILTER_VALUE as filter,
o.[OBJECT_ID] as Id, o.[OBJECT_NAME] as Name, o.DESCRIPTION as Description, o.CREATED as Created,
o.MODIFIED as Modified, u.[LOGIN] as LastModifiedByLogin, o.[OBJECT_NAME] as ObjectName, t.[TEMPLATE_NAME] as TemplateName--,p.[PAGE_NAME] as PageName
FROM
[OBJECT] AS o
LEFT OUTER JOIN [CONTAINER] as cont
on cont.[OBJECT_ID] = o.[OBJECT_ID]
LEFT JOIN [OBJECT_VALUES] AS ov ON
ov.[OBJECT_ID] = o.[OBJECT_ID]
LEFT JOIN [PAGE] AS p ON o.[PAGE_ID] = p.[PAGE_ID]
INNER JOIN [USERS] as u on u.[USER_ID] = o.LAST_MODIFIED_BY INNER JOIN [PAGE_TEMPLATE] as t
on o.[PAGE_TEMPLATE_ID] = t.[PAGE_TEMPLATE_ID] INNER JOIN [site] as s on t.SITE_ID = s.SITE_ID
WHERE
s.SITE_ID = '34' --AND сont.[FILTER_VALUE] is null--like '%fff%'
And it works nice, until I remove the comment.
Here's a mess of joins, still it has sense. I inner join main table with couple of others, and left join with optional, so, that I have a column, that contains cont.FILTER_VALUE as filter, its null in some records, I can get it, but I cant filter by this field.
I get The multi-part identifier "сont.FILTER_VALUE" could not be bound.
I've looked through similar topics, but found no useful information. I don't use any old SQL dialects: everywhere I use INNER/LEFT joins, tried group by and order by, tried to re-order joins - nothing helped. I guess I just don't understand something important about joins, could you tell me, please.
Thanx.
if you wrote it like this:
s.SITE_ID = '34' AND сont.[FILTER_VALUE] is null like '%fff%'
its just wrong syntax. you're missing a column for the LIKE function (in which column does the query suppose to look for the pattern?). if you didnt write it like that, please post what you did write
I don't know why you're getting your error, but try this just in case, while we wait for a better answer:
SELECT FILTER_VALUE as filter
, o.[OBJECT_ID] as Id
, o.[OBJECT_NAME] as Name
, o.DESCRIPTION as Description
, o.CREATED as Created
, o.MODIFIED as Modified
, u.[LOGIN] as LastModifiedByLogin
, o.[OBJECT_NAME] as ObjectName
, t.[TEMPLATE_NAME] as TemplateName
FROM [OBJECT] AS o
INNER JOIN [USERS] as u
ON u.[USER_ID] = o.LAST_MODIFIED_BY
INNER JOIN [PAGE_TEMPLATE] as t
ON o.[PAGE_TEMPLATE_ID] = t.[PAGE_TEMPLATE_ID]
INNER JOIN [site] as s
ON t.SITE_ID = s.SITE_ID
LEFT JOIN [CONTAINER] as cont
ON cont.[OBJECT_ID] = o.[OBJECT_ID]
LEFT JOIN [OBJECT_VALUES] AS ov
ON ov.[OBJECT_ID] = o.[OBJECT_ID]
LEFT JOIN [PAGE] AS p
ON o.[PAGE_ID] = p.[PAGE_ID]
WHERE s.SITE_ID = '34' AND FILTER_VALUE IS NULL
Well, I solved this problem, using CTE, still I wonder, why did I have problems without cte.
This way it works good
with query_CTE
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY o.[OBJECT_ID] asc) as rowNum,
o.[OBJECT_ID] as Id, o.[OBJECT_NAME] as Name, o.DESCRIPTION as Description, o.CREATED as Created,
o.MODIFIED as Modified, u.[LOGIN] as LastModifiedByLogin, o.[OBJECT_NAME] as ObjectName, t.[TEMPLATE_NAME] as TemplateName,p.[PAGE_NAME] as PageName,
s.SITE_ID, t.PAGE_TEMPLATE_ID, p.PAGE_ID, ov.VARIABLE_NAME, ov.VARIABLE_VALUE, cont.FILTER_VALUE, cont.DYNAMIC_CONTENT_VARIABLE, cont.SELECT_START,
cont.SELECT_TOTAL
FROM [OBJECT] AS o
INNER JOIN [USERS] as u
ON u.[USER_ID] = o.LAST_MODIFIED_BY
INNER JOIN [PAGE_TEMPLATE] as t
ON o.[PAGE_TEMPLATE_ID] = t.[PAGE_TEMPLATE_ID]
INNER JOIN [site] as s
ON t.SITE_ID = s.SITE_ID
LEFT JOIN [CONTAINER] as cont
ON cont.[OBJECT_ID] = o.[OBJECT_ID]
LEFT JOIN [OBJECT_VALUES] AS ov
ON ov.[OBJECT_ID] = o.[OBJECT_ID]
LEFT JOIN [PAGE] AS p
ON o.[PAGE_ID] = p.[PAGE_ID]
)
select rowNum,
Id, Name,[Description], Created, Modified, LastModifiedByLogin, ObjectName, TemplateName,PageName
from query_CTE
How would I redesign the below query so that it will recursively loop through entire tree to return all descendants from root to leaves? (I'm using SSMS 2008). We have a President at the root. under him are the VPs, then upper management, etc., on down the line. I need to return the names and titles of each. But this query shouldn't be hard-coded; I need to be able to run this for any selected employee, not just the president. This query below is the hard-coded approach.
select P.staff_name [Level1],
P.job_title [Level1 Title],
Q.license_number [License 1],
E.staff_name [Level2],
E.job_title [Level2 Title],
G.staff_name [Level3],
G.job_title [Level3 Title]
from staff_view A
left join staff_site_link_expanded_view P on P.people_id = A.people_id
left join staff_site_link_expanded_view E on E.people_id = C.people_id
left join staff_site_link_expanded_view G on G.people_id = F.people_id
left join facility_view Q on Q.group_profile_id = P.group_profile_id
Thank you, this was most closely matching what I needed. Here is my CTE query below:
with Employee_Hierarchy (staff_name, job_title, id_number, billing_staff_credentials_code, site_name, group_profile_id, license_number, region_description, people_id)
as
(
select C.staff_name, C.job_title, C.id_number, C.billing_staff_credentials_code, C.site_name, C.group_profile_id, Q.license_number, R.region_description, A.people_id
from staff_view A
left join staff_site_link_expanded_view C on C.people_id = A.people_id
left join facility_view Q on Q.group_profile_id = C.group_profile_id
left join regions R on R.regions_id = Q.regions_id
where A.last_name = 'kromer'
)
select C.staff_name, C.job_title, C.id_number, C.billing_staff_credentials_code, C.site_name, C.group_profile_id, Q.license_number, R.region_description, A.people_id
from staff_view A
left join staff_site_link_expanded_view C on C.people_id = A.people_id
left join facility_view Q on Q.group_profile_id = C.group_profile_id
left join regions R on R.regions_id = Q.regions_id
WHERE C.STAFF_NAME IS NOT NULL
GROUP BY C.STAFF_NAME, C.job_title, C.id_number, C.billing_staff_credentials_code, C.site_name, C.group_profile_id, Q.license_number, R.region_description, A.people_id
ORDER BY C.STAFF_NAME
But I am wondering what is the purpose of the "Employee_Hierarchy"? When I replaced "staff_view" in the outer query with "Employee_Hierarchy", it only returned one record = "Kromer". So when/where can we use "Employee_Hierarchy"?
See:
SQL Server - Simple example of a recursive CTE
MSDN: Recursive Queries using Common Table Expression
SQL Server recursive CTE (this seems pretty much like exactly what you are working on!)
Update:
A proper recursive CTE consist of basically three things:
an anchor SELECT to begin with; that can select e.g. the root level employees (where the Reports_To is NULL), or it can select any arbitrary employee that you define, e.g. by a parameter
a UNION ALL
a recursive SELECT statement that selects from the same, typically self-referencing table and joins with the recursive CTE being currently built up
This gives you the ability to recursively build up a result set that you can then select from.
If you look at the Northwind sample database, it has a table called Employees which is self-referencing: Employees.ReportsTo --> Employees.EmployeeID defines who reports to whom.
Your CTE would look something like this:
;WITH RecursiveCTE AS
(
-- anchor query; get the CEO
SELECT EmployeeID, FirstName, LastName, Title, 1 AS 'Level', ReportsTo
FROM dbo.Employees
WHERE ReportsTo IS NULL
UNION ALL
-- recursive part; select next Employees that have ReportsTo -> cte.EmployeeID
SELECT
e.EmployeeID, e.FirstName, e.LastName, e.Title,
cte.Level + 1 AS 'Level', e.ReportsTo
FROM
dbo.Employees e
INNER JOIN
RecursiveCTE cte ON e.ReportsTo = cte.EmployeeID
)
SELECT *
FROM RecursiveCTE
ORDER BY Level, LastName
I don't know if you can translate your sample to a proper recursive CTE - but that's basically the gist of it: anchor query, UNION ALL, recursive query
I'm currently using joins inside my stored procedures for outputting elements from different tables. An aggressive example
select a.*, b.*, c.*, d.*, e.*, f.* from tableA a
join tableB b on a.id = b.foreignid
join tableC c on b.id = c.foreignid
join tableD d on c.id = d.foreignid
join tableE e on d.id = e.foreignid
join tableF f on e.id = f.foreignid
where a.id = 1
It's getting pretty unhandy to work with when mapping the output to entities in my C# code, since I have to maintain a lot of boilerplate code.
Instead I would look into using multiple resultsets, so that I could map each resultset into an object type in code.
But how would I go around achieving this when I my case the different results would all relate to each other? The examples I've been able to find all revolved around selecting from different tables where the data were not related by foreign keys like mine. If I were to ouput my result in multiple resultsets the only thing I can come up with is something like this
select a.* from tableA
where a.id = 1
select b.* from tableB
join tableA a on a.id = b.foreignid
where a.id = 1
select c.* from tableC
join tableB b on b.id = c.foreignid
join tableA on a.id = b.foreginid
where a.id = 1
select d.* from tableD
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
select e.* from tableE
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
select f.* from tableF
join tableE e on e.id = f.foreignid
join tableD d on d.id = e.foreignid
join tableC c on c.id = d.foreignid
join tableB b on b.id = c.foreignid
join tableA a on a.id = b.foreignid
where a.id = 1
But this is not cleaner, a lot more ineffecient (I would suppose, since there's alot more join statements)
Is it possible to use multiple resultset in this way I'm trying to? I just don't know how I would write the sql statements in the stored proc without having to do massive joins per resultset as in the example. And with the current solution I get an explosion of columns since I join them all together
You can actually return multiplte resultsets from a single SP and consume them in c#, check this post for instance : http://blogs.msdn.com/b/dditweb/archive/2008/05/06/linq-to-sql-and-multiple-result-sets-in-stored-procedures.aspx
It's a lesser known feature but sounds like what you're asking for. You don't have to join them and return them as a flattend rowset, just get the seperate rowsets and piece them together in memory.
Also you may want to read up on ORM frameworks, that could save you a lot of typing that you coud spend on features if it fits your needs.
https://stackoverflow.com/questions/249550/what-orm-frameworks-for-net-do-you-like-best
Regards GJ