Query doesn't seem to yield the correct results - sql

I have a table with three fields, looks like this...........
tblValues
NameFrom NameTo Difference
abbbb arrrr 16
acccc agggg 20
adddd annnn 17
My query looks like this...
Select 'From' = tblValues.NameFrom,
'To' = tblValues.NameTo,
TblValues.Difference,
'Other' = x1.Difference
from tblValues
LEFT JOIN tblValues X1
ON tblValues.NameFrom = X1.NameTo
AND tblValues.NameTo = X1.NameFrom
WHERE tblValues.NameFrom Like '%a%' OR tblValues.NameTo Like '%a%'
ORDER BY tblValues.NameFrom, tblValues.NameTo
I let user search a text value in this case 'a'. I have about 30000 values that are not edited/updated by anyone. They've been entered into this table and have been as they are.
The data looks like this....
From To Difference Other
abbbb arrrr 16 16
.... ....
'Same for all the values - or at least that's what it should be!
The problem i have is that when I run this query there are a few records where OTHER = NULL - even though Difference has a value. Any idea why?

You are picking the value of other with this line
LEFT JOIN tblValues X1 ON tblValues.NameFrom = X1.NameTo
And you display it with this:
'Other' = x1.Difference
A LEFT JOIN means: join this table. If there is no connected record return with NULL. If there is one (or if there are more than one), return with all of them.
For your query, where you are joining the same table as the source table, that means:
Whenever there is no record found, where tblValues.NameFrom = X1.NameTo this field other will stay NULL... Why this happens nobody can tell you from outside...

It looks like you want to change LEFT JOIN to JOIN see a graphical explanation of SQL joins here: https://stackoverflow.com/a/406333/2054629.
Basically left join means
all rows from table A
matching rows of table B if found, else NULL

Your results from the X1 table are NULLs if there are no corresponding NameTo values for Table tblValues NameFrom. The Left Join includes all records from tblValues even if there are no corresponding matches in X1. Use an INNER JOIN:
Select 'From' = tblValues.NameFrom, 'To' = tblValues.NameTo, TblValues.Difference, 'Other' = x1.Difference
from tblValues
INNER JOIN tblValues X1 ON tblValues.NameFrom = X1.NameTo
AND tblValues.NameTo = X1.NameFrom
WHERE tblValues.NameFrom Like '%a%' OR tblValues.NameTo Like '%a%'
ORDER BY tblValues.NameFrom, tblValues.NameTo

Related

JOIN AND CASE MORE AN TABLE

I have 2 tables; the first one ORG contains the following columns:
ORG_REF, ARB_REF, NAME, LEVEL, START_DATE
and the second one WORK contains these columns:
ARB_REF, WORK_STREET - WORK_NUM, WORK_ZIP
I want to do the following: write a select query that search in work and see if the WORK_STREET, WORK_ZIP are duplicate together, then you should look at WORK_NUM. If it is the same then output value ' ok ', but if WORK_NUM is not the same, output 'not ok'
I wrote this SQL query:
select
A.ARB_REF, A.WORK_STREET, A.WORK_NUM, A.WORK_ZIP
case when B.B = 1 then 'OK' else 'not ok' end
from
work A
join
(select
WORK_STREET, WORK_ZIP count(distinct , A.WORK_NUM) B
from
WORK
group by
WORK_STREET, WORK_ZIP) B on B.WORK_STREET = A.WORK_STREET
and B.WORK_ZIP = A.WORK_ZIP
Now I want to join the table ORG with this result I want to check if every address belong to org if it belong I should create a new column result and set it to yes in it (RESULT) AND show the "name" column otherwise set no in 'RESULT'.
Can anyone help me please?
While you can accomplish your result by adding a left outer join to the query you've already started, it might be easiest to just use count() over....
with org_data as (
-- do the inner join before the left join later
select * from org1 o1 inner join org2 o2 on o2.orgid = o1.orgid
)
select
*,
count(*) over (partition by WORK_STREET, WORKZIP) as cnt,
case when o.ARB_REF is not null then 'Yes' else 'No' end as result
from
WORK w left outer join org_data o on o.ARB_REF = w.ARB_REF

SQL Join / Union

I have two statements that I want to merge into one output.
Statement One:
select name from auxiliary_variable_inquiry
where inquiry_idbr_code = '063'
Returns the following list of names:
Name
------------
Affiliates
NetBookValue
Parents
Worldbase
Statement Two:
select name, value from auxiliary_variable_value
where inquiry_idbr_code = '063'
and ru_ref = 20120000008
and period = 200912
Returns the following:
Name Value
-------------------
Affiliates 112
NetBookValue 225.700
I would like to have an output like this:
Name Value
-------------------
Affiliates 112
NetBookValue 225.700
Parents 0
Worldbase 0
So basically, if the second query only returns 2 names and values, I'd still like to display the complete set of names from the first query, with no values. If all four values were returned by both queries, then all four would be displayed.
Sorry I must add, im using Ingres SQL so im unable to use the ISNULL function.
You can do a left join. This ensures that all records from the first table will stay included. Where value is null, no child record was found, and we use coalesce to display 0 in these cases.
select i.name, COALESCE(v.Value,0) from auxiliary_variable_inquiry i
left join auxiliary_variable_value v
on v.inquiry_idbr_code = i.inquiry_idbr_code
and v.ru_ref = 20120000008
and v.period = 200912
where i.inquiry_idbr_code = '063'
I'd recommend a self-JOIN using the LEFT OUTER JOIN syntax. Include your 'extra' conditions from the second query in the JOIN condition, while the first conditions stay in the WHERE, like this:
select a.name, CASE WHEN b.Value IS NULL THEN 0 ELSE b.Value END AS Value
from
auxiliary_variable_inquiry a
LEFT JOIN
auxiliary_variable_inquiry b ON
a.name = b.name and -- replace this with your real ID-based JOIN
a.inquiry_idbr_code = b.inquiry_idbr_code AND
b.ru_ref = 20120000008 AND
b.period = 200912
where a.inquiry_idbr_code = '063'
if i got right, you should use something like:
SELECT i.NAME,
v.NAME,
v.value
FROM auxiliary_variable_inquiry i
LEFT JOIN auxiliary_variable_value v
ON i.inquiry_idbr_code = v.inquiry_idbr_code
WHERE v.ru_ref = 20120000008
AND v.period = 200912

Combine SQL query result with another query statement under one query? (Complicated)

I currently want to combine two SQL queries into one. This is a bit similar to SQL: Taking the result of of query and using it another - combine. Suppose there are two queries:
SQL Statement
1.) SELECT *
FROM (SELECT B.example1
FROM EXAMPLE1A A
INNER JOIN EXAMPLE1B B ON A.ID = B.ID
WHERE A.ABC ='ABC'
ORDER BY A.ORDER_BY ) as colstate
2.) SELECT colstate
FROM EXAMPLE_TABLE
WHERE EFG LIKE '%'
AND BGTHAN >= '1'
AND SMTHAN <= '100'
ORDER BY ORDER_BY ASC
I want to use the result in query 1.) as the colstate (column statement) in query 2.). But:
What Have I tried is:
SELECT (SELECT B.example1
FROM EXAMPLE1A A
INNER JOIN EXAMPLE1B B
ON A.ID = B.ID
WHERE A.ABC ='ABC'
ORDER BY A.ORDER_BY )
FROM EXAMPLE_TABLE
WHERE EFG LIKE '%'
AND BGTHAN >= '1'
AND SMTHAN <= '100'
ORDER BY ORDER_BY ASC
And it turns out to be Error: Scalar subquery is only allowed to return a single row, how should I replace the "=" into "IN"? Or is my statement totally wrong?
"Combine two queries into one" - that's not a good specs. Try to find out what exactly you want to get as a FLAT 2-dimensional table, think of nested SELECTs as of nested loops where the inner one can only set a single value for parent's row. Like this:
[Outer loop - parent row]
[Inner loop - children rows]
// all you can do here is change a single parent's field to anything
// like constant/sum/avg/topmost/ugly-subquery-returning-a-single-result
[/Inner loop]
[/Outer loop]
The error says that query you are using as column statement must return at most a single row.
It should probably look something like this:
SELECT (SELECT B.example1
FROM EXAMPLE1A A
INNER JOIN EXAMPLE1B B
ON A.ID = B.ID
WHERE A.ABC ='ABC'
AND A.SOME_COLUMN = E.SOMECOLUMN // retrieve only relevant data for this row
ORDER BY A.ORDER_BY )
FROM EXAMPLE_TABLE E
WHERE EFG LIKE '%'
AND BGTHAN >= '1'
AND SMTHAN <= '100'
ORDER BY ORDER_BY ASC

SQL: Want to alter the conditions on a join depending on values in table

I have a table called Member_Id which has a column in it called Member_ID_Type. The select statement below returns the value of another column, id_value from the same table. The join on the tables in the select statement is on the universal id column. There may be several entries in that table with this same universal id.
I want to adjust the select statement so that it will return the id_values for entries that have member_id_type equal to '7'. However if this is null then I want to return records that have member_id_type equal to '1'
So previously I had a condition on the join (commented out below) but that just returned records that had member_id_type equal to '7' and otherwise returned null.
I think I may have to use a case statement here but I'm not 100% sure how to use it in this scenario
SELECT TOP 1 cm.Contact_Relation_Gid,
mc.Universal_ID,
mi.ID_Value,
cm.First_Name,
cm.Last_Name,
cm.Middle_Name,
cm.Name_Suffix,
cm.Email_Address,
cm.Disability_Type_PKID,
cm.Race_Type_PKID,
cm.Citizenship_Type_PKID,
cm.Marital_Status_Type_PKID,
cm.Actual_SSN,
cm.Birth_Date,
cm.Gender,
mc.Person_Code,
mc.Relationship_Code,
mc.Member_Coverage_PKID,
sc.Subscriber_Coverage_PKID,
FROM Contact_Member cm (NOLOCK)
INNER JOIN Member_Coverage mc (NOLOCK)
ON cm.contact_relation_gid = mc.contact_relation_gid
AND mc.Record_Status = 'A'
INNER JOIN Subscriber_Coverage sc (NOLOCK)
ON mc.Subscriber_Coverage_PKID = sc.Subscriber_Coverage_PKID
AND mc.Record_Status = 'A'
LEFT outer JOIN Member_ID mi ON mi.Universal_ID = cm.Contact_Gid
--AND mi.Member_ID_Type_PKID='7'
WHERE cm.Contact_Relation_Gid = #Contact_Relation_Gid
AND cm.Record_Status = 'A'
Join them both, and use one if the other is not present:
select bt.name
, coalesce(eav1.value, eav2.value) as Value1OrValue2
from BaseTable bt
left join EavTable eav1
on eav1.id = bt.id
and eav1.type = 1
left join EavTable eav2
on eav2.id = bt.id
and eav2.type = 2
This query assumes that there is never more than one record with the same ID and Type.

Doing an Update Ignore in SQL Server 2005

I have a table where I wish to update some of the rows. All the fields are not null. I'm doing a sub-query, and I wish to update the table with the non-Null results.
See Below for my final answer:
In MySQL, I solve this problem by doing an UPDATE IGNORE. How do I make this work in SQL Server 2005? The sub-query uses a four-table Join to find the data to insert if it exists. The Update is being run against a table that could have 90,000+ records, so I need a solution that uses SQL, rather than having the Java program that's querying the database retrieve the results and then update those fields where we've got non-Null values.
Update: My query:
UPDATE #SearchResults SET geneSymbol = (
SELECT TOP 1 symbol.name FROM
GeneSymbol AS symbol JOIN GeneConnector AS geneJoin
ON symbol.id = geneJoin.geneSymbolID
JOIN Result AS sSeq ON geneJoin.sSeqID = sSeq.id
JOIN IndelConnector AS joiner ON joiner.sSeqID = sSeq.id
WHERE joiner.indelID = #SearchResults.id ORDER BY symbol.id ASC)
WHERE isSNV = 0
If I add "AND symbol.name IS NOT NULL" to either WHERE I get a SQL error. If I run it as is I get "adding null to a non-null column" errors. :-(
Thank you all, I ended up finding this:
UPDATE #SearchResults SET geneSymbol =
ISNULL ((SELECT TOP 1 symbol.name FROM
GeneSymbol AS symbol JOIN GeneConnector AS geneJoin
ON symbol.id = geneJoin.geneSymbolID
JOIN Result AS sSeq ON geneJoin.sSeqID = sSeq.id
JOIN IndelConnector AS joiner ON joiner.sSeqID = sSeq.id
WHERE joiner.indelID = #SearchResults.id ORDER BY symbol.id ASC), ' ')
WHERE isSNV = 0
While it would be better not to do anything in the null case (so I'm going to try to understand the other answers, and see if they're faster) setting the null cases to a blank answer also works, and that's what this does.
Note: Wrapping the ISNULL (...) with () leads to really obscure (and wrong) errors.
with UpdatedGenesDS (
select joiner.indelID, name, row_number() over (order by symbol.id asc) seq
from
GeneSymbol AS symbol JOIN GeneConnector AS geneJoin
ON symbol.id = geneJoin.geneSymbolID
JOIN Result AS sSeq ON geneJoin.sSeqID = sSeq.id
JOIN IndelConnector AS joiner ON joiner.sSeqID = sSeq.id
WHERE name is not null ORDER BY symbol.id ASC
)
update Genes
set geneSymbol = upd.name
from #SearchResults a
inner join UpdateGenesDs upd on a.id = b.intelID
where upd.seq =1 and isSNV = 0
this handles the null completely as all are filtered out by the where predicate (can also be filtered by join predicate if You wish. Is it what You are looking for?
Here's another option, where only those rows in #SearchResults that are succesfully joined will be udpated. If there are no null values in the underlying data, then the inner joins will pull in no null values, and you won't have to worry about filtering them out.
UPDATE #SearchResults
set geneSymbol = symbol.name
from #SearchResults sr
inner join IndelConnector AS joiner
on joiner.indelID = sr.id
inner join Result AS sSeq
on sSeq.id = joiner.sSeqID
inner join GeneConnector AS geneJoin
on geneJoin.sSeqID = sSeq.id
-- Get "lowest" (i.e. first if listed alphabetically) value of name for each id
inner join (select id, min(name) name
from GeneSymbol
group by id) symbol
on symbol.id = geneJoin.geneSymbolID
where isSNV = 0 -- Which table is this value from?
(There might be some syntax problems, without tables I can't debug it)