SQL - merge two queries - sql

I have the two below queries, the first query returns a list of externalId.
select e.externalId
from data_entity db
inner join assign_entity a on db.fk_assign = a.assignmentId
inner join exercise_entity e on a.fk_exercice = e.externalId;
The second query returns an internalId of each externalId returned by the first query:
select me.internal_id
from entity me
inner join entity_roles r on me.externalid = r.entity_externalid
where r.roles = 'c9237a21-f6da-4ebe-81b0-ddecd51da86b';
How can I merge the two queries in a single query to return for each externalId its internalId like this?

This should do what is required I think. Since there is no fiddle/data present, I can not test it.
with external as
(select e.externalId as externalId from data_entity db
inner join assign_entity a on db.fk_assign = a.assignmentId
inner join exercise_entity e on a.fk_exercice = e.externalId)
select distinct e.externalId, me.internal_id from entity me
inner join entity_roles r on me.externalid = r.entity_externalid
inner join external e on r.roles = e.externalId;

You can use EXISTS:
select me.internal_id, me.externalId
from entity me
inner join entity_roles r on me.externalid = r.entity_externalid
WHERE r.roles = 'c9237a21-f6da-4ebe-81b0-ddecd51da86b'
and exists (
select * from data_entity db
inner join assign_entity a on db.fk_assign = a.assignmentId
inner join exercise_entity e on a.fk_exercice = e.externalId
where e.externalId = me.externalId
);
Probably this query is simpler than what it is now, but based only on your pictures and queries this would do.
PS: Next time, please provide a good sample of your data tables. Pictures do not help much to anyone.

Without some data or a fiddle it is difficult to help, but I think this should work:
SELECT me.internal_id,
me.externalid
FROM entity me
INNER JOIN entity_roles r
ON me.externalid = r.entity_externalid
WHERE r.roles = 'c9237a21-f6da-4ebe-81b0-ddecd51da86b'
AND EXISTS (SELECT *
FROM data_entity db
INNER JOIN exercise_entity e
ON a.fk_exercice = e.externalid
INNER JOIN assign_entity a
ON db.fk_assign = a.assignmentid
WHERE me.externalid = e.externalid);

Related

SQL to LINQ to SQL expression without Join

While converting an SQL query below query with navigation in Entity Framework
SELECT DISTINCT
a.ApplicationID, eA.EmployeeID AS AppID, eA.EmailID AS AppEmail,
eA.Title + eA.Name AS Applicant, eR.EmployeeID, eR.Title + eR.Name
AS Employee, eR.EmailID AS Email, r.Title AS Role, r.RoleID, t .Title AS
Task, t .TaskID, d .ShortName AS AppDeptSN, a.Reminders, '' AS SubTaskID
FROM
dbo.Application_TaskLog AS a INNER JOIN
dbo.Task AS t ON t .TaskID = a.TaskID INNER JOIN
dbo.Role AS r ON r.RoleID = t .RoleID INNER JOIN
dbo.Application_Role AS ar ON ar.ApplicationID = a.ApplicationID AND
ar.RoleID = t .RoleID INNER JOIN
dbo.Employee AS eR ON eR.EmployeeID = ar.EmployeeID INNER JOIN
dbo.Application AS app ON app.ApplicationID = a.ApplicationID INNER JOIN
dbo.Employee AS eA ON eA.EmployeeID = app.EmployeeID LEFT OUTER JOIN
dbo.Departments AS d ON eA.DepartmentID = d .DepartmentID
I wrote the following function to populate gridview
public List<Application_TaskLog> GetAppTaskLogDistinct(int appID)
{
var context = new FPSDB_newEntities();
var data = (from atl in context.Application_TaskLog
where atl.ApplicationID == appID
&& !atl.Application.ApplicationClosed && !atl.Completed
select atl).Distinct().ToList();
return data;
}
Distinct() is not working as it works in the SQL. I am confused how to use Distinct as I have used in SQL
context.Application_TaskLog already returns distinct Application_TaskLog records and there's nothing in the query that duplicates them, so Distinct() doesn't make any difference

how to select some fields from tables in CakePHP

I tried to make query in cakephp with joins, but i want to get more fileds,
Here the query sql :
SELECT
sd.debut,
sd.fin,
fr.id,
f.id as formtaion_id,
s.id as seance_id,
fr.nom as formateur,
f.nom as formation,
r.title,
f.module,
sd.module as partie ,
f.couleur
FROM seances s
INNER JOIN formations f on s.formation_id = f.id
INNER JOIN seances_dates sd on s.id = sd.seance_id
INNER JOIN salles sa on sa.id = s.salle_id
INNER JOIN regions r on r.id = sa.region_id
INNER JOIN presence_formateurs pf ON pf.seance_id = s.id
INNER JOIN formateurs fr ON fr.id = pf.formateur_id
WHERE fr.archived = 0
AND fr.deleted is null
AND (
(sd.debut between '".$from."' and '".$to."')
OR
(sd.fin between '".$from."' and '".$to."')
)
GROUP BY sd.id
ORDER BY sd.debut
please help me to make that query in cakephp :
ClassRegistry::init('seance')->find('all'....
You should read very carefully
1. How to Retrieve data in CakePHP and
2. How to make Relation with different table

Query returns no records

Hello i am making schema for purchasing orders these orders can be ordered by certain user and then received by another user.
so i created the below schema.
Schema
The issue is when UserID column in PurchaseOrders and Deliveries tables has different values the query returns no records.
Query
SELECT
dbo.Users.FirstName,
dbo.Users.LastName,
dbo.PurchaseOrders.PurchaseOrderDate,
dbo.Deliveries.ExpectedDeliveryDate,
dbo.Deliveries.ActualDeliveryDate
FROM dbo.PurchaseOrders
INNER JOIN dbo.Users
ON dbo.PurchaseOrders.UserID = dbo.Users.UserID
INNER JOIN dbo.Deliveries
ON dbo.PurchaseOrders.PurchaseOrderID = dbo.Deliveries.PurchaseOrderID
AND dbo.Users.UserID = dbo.PurchaseOrders.UserID
AND dbo.Users.UserID = dbo.Deliveries.UserID
You need two different joins to Users. You also need to learn to use table aliases:
SELECT pu.FirstName as purchase_FirstName, pu.LastName as purchase_LastName,
du.FirstName as delivery_FirstName, du.LastName as delivery_LastName,
po.PurchaseOrderDate,
d.ExpectedDeliveryDate, d.ActualDeliveryDate
FROM dbo.PurchaseOrders po JOIN
dbo.Deliveries d
ON po.PurchaseOrderID = d.PurchaseOrderID JOIN
dbo.Users pu
ON p.UserID = pu.UserID JOIN
dbo.Users du
ON d.UserId = du.UserId;
Your query returns no records because of this condition:
AND dbo.Users.UserID = dbo.PurchaseOrders.UserID
AND dbo.Users.UserID = dbo.Deliveries.UserID
This obviously means that dbo.PurchaseOrders.UserID = dbo.Deliveries.UserID. So, if this is not true, then no records match the condition.
When you use Inner Join, if the data doesnt match, you will not get any records. You need to use LEFT JOIN and also the second join doesnt need condition with user id. Try the below query.
SELECT
dbo.Users.FirstName,
dbo.Users.LastName,
dbo.PurchaseOrders.PurchaseOrderDate,
dbo.Deliveries.ExpectedDeliveryDate,
dbo.Deliveries.ActualDeliveryDate
FROM dbo.PurchaseOrders
INNER JOIN dbo.Users
ON dbo.PurchaseOrders.UserID = dbo.Users.UserID
LEFT JOIN dbo.Deliveries
ON dbo.PurchaseOrders.PurchaseOrderID = dbo.Deliveries.PurchaseOrderID

How to select multiple many to many in relation with a single table

I'm currently working with database, but I've got stuck with a select query.
However, I'm not database expert.
The query should return the data from a table that has two relationships of many to many.
This is my tables Diagram that would shows the concept of my question
The Select Query should View three columns, which are VidTbl.Name, ActorTbl.Name and SubTitelTbl.name.
So, I've read and search in the Internet and I've given tries
First try
SELECT
VidTbl.NAME AS Video_Titel_Name,
ActorTbl.NAME AS Actor_Name
FROM ActorInVid
INNER JOIN VidTbl
ON VidTbl.Id = ActorInVid.FKVidId
INNER JOIN ActorTbl
ON ActorTbl.Id = ActorInVid.FKActorId
UNION all
SELECT
VidTbl.NAME AS Video_Titel_Name,
SubTitelTbl.NAME AS SubTitel_Langu
FROM SubTitelInVid
INNER JOIN VidTbl
ON VidTbl.Id = SubTitelInVid.FKVidId
INNER JOIN SubTitelTbl
ON SubTitelTbl.Id = SubTitelInVid.FKSTId
The Result I've got, it was wrong
Then I tried another way to solve this problem, but again I've got another error
second try
SELECT Temp1.*
From (SELECT VidTbl.Id AS Video_Id,
VidTbl.NAME AS Video_Titel_Name,
ActorTbl.NAME AS Actor_Name
FROM ActorInVid
INNER JOIN VidTbl
ON VidTbl.Id = ActorInVid.FKVidId
INNER JOIN ActorTbl
ON ActorTbl.Id = ActorInVid.FKActorId) AS Temp1
SELECT Temp2.*
FROM (SELECT VidTbl.Id AS Video_Id,
SubTitelTbl.NAME AS SubTitel_Langu
FROM SubTitelInVid
INNER JOIN VidTbl
ON VidTbl.Id = SubTitelInVid.FKVidId
INNER JOIN SubTitelTbl
ON SubTitelTbl.Id = SubTitelInVid.FKSTId) AS Temp2
SELECT *
FROM VidTbl
INNER JOIN Temp1
on Temp1.Video_Id = VidTbl.Id
INNER JOIN Temp2
on Temp2.Video_Id = VidTbl.Id
The error, I've got in the last select that was wrong
Thanks a lot for your help any ways
I wish that my question is clear and useful
Thanks again.
You are close. This should work...
SELECT
VidTbl.Name,
ActorTbl.Name,
SubTitelTbl.name
FROM VidTbl
INNER JOIN ActorInVid ON VidTbl.Id = ActorInVid.FKVidId
INNER JOIN ActorTbl ON ActorTbl.Id = ActorInVid.FKActorId
INNER JOIN SubTitelInVid ON VidTbl.Id = SubTitelInVid.FKVidId
INNER JOIN SubTitelTbl ON SubTitelTbl.Id = SubTitelInVid.FKSTId
SELECT DISTINCT vt.Name, at.Name, st.Name
FROM VidTbl vt
JOIN ActionInVid aiv ON aiv.VidId = vt.Id
JOIN SubtitleInVid siv ON siv.VidId = vt.Id
JOIN ActorTbl at ON at.Id = aiv.ActorId
JOIN SubTitleTbl st ON st.Id = siv.STId

sql query sum bringing back different results

I have the following two queries below, the Total is coming back different, but I am adding the sums in each of the query the same way. Why is the total coming back different?
select [Total Children] = (SUM(demo.NumberOfPreschoolers) + SUM(demo.NumberOfToddlers) + SUM(demo.NumberOfInfants)),
County = co.Description
from ClassroomDemographics as demo
inner join Classrooms as c on demo.Classroom_Id = c.Id
inner join Sites as s on c.Site_Id = s.Id
inner join Profiles as p on s.Profile_Id = p.Id
inner join Dictionary.Counties as co on p.County_Id = co.Id
where co.Description = 'MyCounty'
Group By co.Description
select [Number Of DLL Children] = SUM(cd.NumberOfLanguageSpeakers),
[Total Children] = (SUM(demo.NumberOfPreschoolers) + SUM(demo.NumberOfToddlers) + SUM(demo.NumberOfInfants)),
County = co.Description
from ClassroomDLL as cd
inner join Classrooms as c on cd.Classroom_Id = c.Id
inner join Sites as s on c.Site_Id = s.Id
inner join Profiles as p on s.Profile_Id = p.Id
inner join Dictionary.Counties as co on p.County_Id = co.Id
inner join ClassroomDemographics as demo on c.Id = demo.Classroom_Id
where co.Description = 'MyCounty'
Group by co.Description
Just a quick glance over the two querties, I would presume that:
inner join ClassroomDemographics as demo on c.Id = demo.Classroom_Id
in the second query is excluding results that are in the first query, therefor the aggregated values will be different.
Your join to the Classrooms table is joining with an extra table in the 2nd query.
Query 1:
from ClassroomDemographics as demo
inner join Classrooms as c on demo.Classroom_Id = c.Id
Query 2:
from ClassroomDLL as cd
inner join Classrooms as c on cd.Classroom_Id = c.Id
...
inner join ClassroomDemographics as demo on c.Id = demo.Classroom_Id
My bet is that the ClassroomDLL table has less data in it, or has rows with a null for one of the join criteria columns, either of which could exclude rows from the results and throw your aggregate totals off.