Issue with SQL query with join of 2 tables - sql

I have two different tables in my SQL Server (Dorig and Dotes) that are connected by column id_dotes present in both.
I need a help for a query that returns a result of Dorig with column NumeroDocRif, present only in table Dotes, where this last one must to be extracted when this condition is true
dorig.id_dorig = dorig.id_dorig_evade
I try to create this query but it doesn't work completely well:
SELECT
dorig.Id_Dorig, dotes.NumerodocRif
FROM
dorig
LEFT JOIN
dotes ON dotes.id_Dotes = dorig.id_Dotes
WHERE
id_dorig IN (SELECT DISTINCT id_dorig_evade
FROM dorig
WHERE id_dotes = dorig.id_dotes)
Could you please help me?
Many thanks in advance

create table dorig (id_dorig int, id_dotes int, id_dorig_evade int);
create table dotes(id_dotes int, numerodocrif varchar(50));
insert into dorig values(16934,3116,4894);
insert into dorig values(4894,1090,null);
insert into dotes values(1090,'7000079957');
SELECT d.Id_Dorig,d.id_dotes,dt.NumerodocRif
FROM dorig d inner join dorig dg
on d.id_dorig_evade =dg.id_dorig
inner JOIN dotes dt ON dt.id_Dotes = dg.id_Dotes
Id_Dorig
id_dotes
NumerodocRif
16934
3116
7000079957
db<>fiddle here

It seems like all you should need to do is replace the statement you already wrote out in the text of your question into your second WHERE clause:
SELECT dorig.Id_Dorig,dotes.NumerodocRif
FROM dorig
LEFT JOIN dotes ON dotes.id_Dotes = dorig.id_Dotes
WHERE id_dorig IN
(SELECT DISTINCT id_dorig_evade FROM dorig
WHERE dorig.id_dorig = dorig.id_dorig_evade)

Related

SQL How to get full Array in a temporary table with condition?

Well, I am really sorry because my explanation was so poor. Thank you for all the answers.
I will explain better what should be the output and what is my question.
So, first of I have an array of tagCodes like ('code0','code1','code2').
Then I have a table that contains Codes and TagTypeId.
I would like to get into a temporary table all the codes I passed in the array with their TagTypeId. So a table like:
Code
TagTypeId
903420012408181609019A18
2456
903420012408181609019A18
2135
TestCodeNull
null
So my attempt was this one:
SELECT Tags.Code AS tagCode, Tags.TagTypeId, TagTypes.Code AS tagType
INTO #TempTable
FROM Tags JOIN TagTypes ON Tags.TagTypeId = TagTypes.Id
WHERE Tags.Code IN ('903420012408181609019A18','90341808151313061101E938', 'TestCodeNull')
SELECT * FROM #TempTable;
But I dont get the codes that are not in the Tag table.
I did this an it seems to be working as intended:
CREATE TABLE #TestTable (tagCode NVARCHAR(25) NOT NULL, TagTypeId INT NULL, tagType NVARCHAR(MAX))
INSERT INTO #TestTable (tagCode) VALUES ('903420012408181609019A18'),('00007E08190D0A34E1F524D0'),('00007E08190D0B25E1F5A98B')
UPDATE #TestTable SET TagTypeId = Tags.TagTypeId, tagType = TagTypes.Code FROM #TestTable
LEFT JOIN Tags ON (#TestTable.tagCode = Tags.Code)
LEFT JOIN TagTypes ON (Tags.TagTypeId = TagTypes.Id)
SELECT * FROM #TestTable;
I think what you mean that 'TestCodeNull' does not exist in tags so you want to show null for 'TestCodeNull' in which case a join may be more appropriate. for example
SELECT S.CODE,Tags.Code AS tagCode, Tags.TagTypeId,
TagTypes.Code AS tagType
INTO #TempTable
FROM (select '903420012408181609019A18' code
union all select '90341808151313061101E938'
union all select 'TestCodeNull') s
left join Tags on tags.code = s.code
left JOIN TagTypes ON Tags.TagTypeId = TagTypes.Id
SELECT * FROM #TempTable;

SQL can not refer table in from clause within where

I have a simple SQL query used in oracle 11g
select something
from sc
where sc.column satisfies something
but I can not refer SC in the where composite, any one can help explain this, thanks in advance.
---second edit: I tested the sql command in oracle 19c it works but in 11g it does not work.
table contents
create table sc(
sno varchar2(10),
cno varchar2(10),
score number(4,2),
constraint pk_sc primary key (sno,cno)
);
example data
insert into sc values ('s001','c001',78.9);
insert into sc values ('s002','c001',80.9);
insert into sc values ('s003','c001',81.9);
insert into sc values ('s004','c001',60.9);
insert into sc values ('s001','c002',82.9);
insert into sc values ('s002','c002',72.9);
insert into sc values ('s003','c002',81.9);
insert into sc values ('s001','c003','59');
sql command
SELECT SNO
FROM SC A
WHERE 0 = (SELECT COUNT(*)
FROM
(SELECT B.CNO
FROM SC B
WHERE B.SNO = 's001'
MINUS
SELECT C.CNO
FROM SC C
WHERE A.SNO = C.SNO) --this is the error location, oracle reports invalid identifier A.
);
I would try a exists clause instead of where 0 =
SELECT SNO
FROM SC A
WHERE not exists (SELECT B.CNO
FROM SC B
WHERE B.SNO = 's001'
MINUS
SELECT C.CNO
FROM SC C
WHERE A.SNO = C.SNO) --this is the error location, oracle reports undefined A.
I'm assuming you want to return where there is not a match?
If you're trying to get the CNO that are not only in SNO 's001'.
Then maybe this.
SELECT DISTINCT SNO, cno
FROM SC sc
WHERE SNO = 's001'
AND EXISTS (
SELECT 1
FROM SC sc2
WHERE sc2.CNO = sc.CNO
AND sc2.SNO != sc.SNO
)

Copy values from one table to another in SQL

I have 2 tables. I need to update all rows of table 1 with the values in specific columns from table 2. They have the same structure.
UPDATE #TempTable
SET [MyColumn] =
(
SELECT [MyColumn]
FROM
[udf_AggregateIDs] (#YearId) AS [af]
INNER JOIN [MyForm] ON
(
[af].[FormID] = [MyForm].[FormID] AND
[af].[FormID] = #MyFormId
)
WHERE [Description] = [MyForm].[Description]
)
I get an error saying Subquery returned more than 1 value. I only added the where clause in because i thought sql is struggling to match the rows, but both tables have the same rows.
It should return multiple values because i'm trying to copy across all rows for MyColumn from the one table to the other.
Ideas?
is Description unique ?
select [Description], count(*) from [MyForm] group by [Description] having count(*)>1
You don't need a sub query..just join the tables..
same type of question has been answered here. Hope it helps.
Have to guess here because your query isn't self-documenting. Does MyColumn come from the function? Does #TempTable have a description column? Who knows, because you didn't prefix them with an alias? Try this. You may have to adjust since you know your schema and we don't.
UPDATE t
SET [MyColumn] = func.MyColumn -- have to guess here
FROM dbo.[udf_AggregateIDs] (#YearId) AS func
INNER JOIN dbo.MyForm AS f
ON func.FormID = f.FormID
INNER JOIN #TempTable AS t
ON t.Description = f.Description -- guessing here also
WHERE f.FormID = #MyFormID;

How can I select a subset of columns from a table when relevant in an outer join?

select a.cust_xref_id, a.est_hour, a.phone_nbr as number, a.credit_calls, a.credit_rpcs, b.sdp_calls
from #temp0 a
full outer join #temp2 b
on a.cust_xref_id = b.sdp_cust_xref_id
and a.est_hour = b.sdp_hour
and a.phone_nbr = b.sdp_phone
Is there a way to get the data from table b with regard to sdp_cust_xref_id, sdp_hour, and sdp_phone when the data does not exist in both tables via the join? If b.sdp_calls does exist, the column values are null.
I read it a few more times and I think I know what you want. Try this. It will give you the values from table b if they are NULL in a:
select COALESCE(a.cust_xref_id, b.sdp_cust_xref_id) as cust_xref_id,
COALESCE(a.est_hour, b.spd_hour) as est_hour,
COALESCE(a.phone_nbr, b.spd_phone) as number,
a.credit_calls,
a.credit_rpcs,
b.sdp_calls
from #temp0 a
full outer join #temp2 b
on a.cust_xref_id = b.sdp_cust_xref_id
and a.est_hour = b.sdp_hour
and a.phone_nbr = b.sdp_phone

Help with basic sql query

This example is simplified. I have the following design:
http://img835.imageshack.us/i/designyi.jpg/
I have inserted test data like this:
INSERT INTO Period VALUES ('Survey for 2011', 1)
INSERT INTO EvalQuestion VALUES('How do...')
INSERT INTO EvalQuestion VALUES('How many...')
INSERT INTO EvalQuestion VALUES('Which is....')
INSERT INTO EvalQuestion_Period VALUES (1, 1)
INSERT INTO EvalQuestion_Period VALUES (1, 2)
INSERT INTO EvalQuestion_Period VALUES (1, 3)
INSERT INTO Employee VALUES ('Peter', 'Smith')
INSERT INTO Employee VALUES ('Britney', 'Spears')
INSERT INTO EvalAnswer VALUES(1,'Fine',1)
INSERT INTO EvalAnswer VALUES(2,'45',1)
INSERT INTO EvalAnswer VALUES(3,'I don´t know',1)
INSERT INTO EvalAnswer VALUES(1,'Fine again',2)
INSERT INTO EvalAnswer VALUES(2,'45 again',2)
INSERT INTO EvalAnswer VALUES(3,'I don´t know again',2)
I run the following query to get question and answer for Peter:
Select Name, Answer
from EvalQuestion eq
LEFT JOIN EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion
LEFT JOIN EvalAnswer ea ON ea.FK_EvalQuestion_Period = eqp.Id
where ea.FK_Employee = 1
Result set:
Name Answer
-----------------------
How do... Fine
How many... 45
Which is.... I don´t know
This looks good. If I delete one of Peters Answers like this:
Delete from EvalAnswer where ID= 1
And run the same query I only get two rows, like this
Name Answer
-----------------------
How many... 45
Which is.... I don´t know
I need my question in the result set even if it is unanswered, like this:
Name Answer
-----------------------
How do.... NULL
How many... 45
Which is.... I don´t know
Any tips? Thanks
Your "left join" is actually an LEFT OUTER JOIN (despite other answers): the join type is implied by LEFT or RIGHT with OUTER being optional
When you use WHERE ea.FK_Employee = 1 then you are changing this to an INNER JOIN because you are not allowing for missing rows. You need to filter first (that is restrict rows on EvalAnswer before the join). This is because WHERE is processed after JOIN..ON logically.
Try this with a derived, filtered table:
Select Name, Answer
from EvalQuestion eq
LEFT JOIN
EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion
LEFT JOIN
(SELECT * FROM EvalAnswer
where FK_Employee = 1
) ea ON ea.FK_EvalQuestion_Period = eqp.Id
Or filter in the ON condition:
Select Name, Answer
from EvalQuestion eq
LEFT JOIN
EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion
LEFT JOIN
EvalAnswer ea ON ea.FK_EvalQuestion_Period = eqp.Id AND ea.FK_Employee = 1
Any time you want to return 1 or more rows from the original table, you can use an outer join. So your query would be:
Select Name, Answer
from EvalQuestion eq
LEFT JOIN EvalQuestion_Period eqp ON eq.Id = eqp.FK_EvalQuestion
LEFT OUTER JOIN EvalAnswer ea ON ea.FK_EvalQuestion_Period = eqp.Id
where ea.FK_Employee = 1
This will return nulls for the values from EvalAnswer when no corresponding records exist, but otherwise will function exactly as the LEFT JOIN.