SQL Select from table twice - sql

I am trying to select from the same table twice within SQL.
I have a POLICIES table that has an index (NEXTPOLICYID) that refers to itself.
I need to compare the current premium with the estimated premium.
How can I get a result that shows the following on the same result row?
t1 = Current
t2 = Future
End result should be:
t1.POLICIES_ID | t1.WRITTEN_PREMIUM | t2.POLICIES_ID | t2.ESTIMATED_PREMIUM
This is what I have right now, and I am getting an error on my join statement, but I fear that is not my only problem.
SELECT
t1.POLICIES_ID, t1.WRITTEN_PREMIUM, t1.NEXTPOLICYID, t2.ESTIMATED_PREMIUM
FROM
POLICIES t1 JOIN
POLICIES t2
ON t1.NEXTPOLICYID = t2.POLICIES_ID
I am getting the following error:
Message: odbc_exec(): SQL error: [Rocket U2][UVODBC][1401233]Error ID: 29 Severity: ERROR Facility: FPSRVERR - Line 5, column 17 (around "JOIN"): Syntax error., SQL state S1000 in SQLExecDirect
This is an ODBC Connection to a uniVerse database, I have tested this with many other functions and it works fine. This error tells me it does not like something before the JOIN statement.
Thank you

Apart from the comma, the only other issues are:
You don't need to include t2.POLICIES_ID in the select list, because you have t1.NEXTPOLICYID
You might want to consider a left outer join, to keep policies that have no next policy.
The query might be:
SELECT t1.POLICIES_ID, t1.WRITTEN_PREMIUM, t1.NEXTPOLICYID,
t2.ESTIMATED_PREMIUM
FROM POLICIES t1 JOIN
POLICIES t2
ON t1.NEXTPOLICYID = t2.POLICIES_ID;

This:
SELECT
t1.POLICIES_ID,
t1.WRITTEN_PREMIUM
t1.NEXTPOLICYID,
t2.ESTIMATED_PREMIUM,
t2.POLICIES_ID
FROM
POLICIES t1,
JOIN POLICIES t2 ON t1.NEXTPOLICYID = t2.POLICIES_ID
has some issues with commas in the wrong places and should be:
SELECT
t1.POLICIES_ID,
t1.WRITTEN_PREMIUM,
t1.NEXTPOLICYID,
t2.ESTIMATED_PREMIUM,
t2.POLICIES_ID
FROM
POLICIES t1
JOIN POLICIES t2 ON t1.NEXTPOLICYID = t2.POLICIES_ID
I'm guessing that's the reason for the error.

Related

SQL join on multiple columns or on single calculated column

I'm migrating the backend a budget database from Access to SQL Server and I ran into an issue.
I have 2 tables (let's call them t1 and t2) that share many fields in common: Fund, Department, Object, Subcode, TrackingCode, Reserve, and FYEnd.
If I want to join the tables to find records where all 7 fields match, I can create an inner join using each field:
SELECT *
FROM t1
INNER JOIN t2
ON t1.Fund = t2.Fund
AND t1.Department = t2.Department
AND t1.Object = t2.Object
AND t1.Subcode = t2.Subcode
AND t1.TrackingCode = t2.TrackingCode
AND t1.Reserve = t2.Reserve
AND t1.FYEnd = t2.FYEnd;
This works, but it runs very slowly. When the backend was in Access, I was able to solve the problem by adding a calculated column to both tables. It basically, just concatenated the fields using "-" as a delimiter. The revised query is as follows:
SELECT *
FROM t1 INNER JOIN t2
ON CalculatedColumn = CalculatedColumn
This looks cleaner and runs much faster. The problem is when I moved t1 and t2 to SQL Server, the same query gives me an error message:
I'm new to SQL Server. Can anyone explain what's going on here? Is there a setting I need to change for the calculated column?
Posting this as an answer from my comment.
Usually, this is an issue with mismatched Data types between the two columns referenced. Check and make sure the data types of the two fields (CompositeID) are the same.
You have to calculate the columns before joining them as the ON clause can only access columns for the table.
It is no good to have two identical tables anyway so you should rethink your design completely.
SELECT t1a.*,t2a.*
FROM (SELECT CalculatedColumn, * FROM t1) t1a INNER JOIN (SELECT CalculatedColumn, * FROM t2 ) t2a
ON t1a.CalculatedColumn = t2a.CalculatedColumn

Left Join with Partial match SQL Server

I have 2 tables in SQL Server that I am trying to make a left join from so that all records from table1 are shown and any data from table2 is shown if it exists. They are as follows
Table1
id Customername Jobid
--------------------------------
2754444 Jones 123
2854233 Smith 234
Table2
key Location
-----------------------------
FD#2754444 London
FEC#2854233 Liverpool
I can get an inner join query to work as below - but I obviously get only matching records, (which I dont want - I want all records from table1 and any matching values from table2)
This works:
$query = "select distinct table1.id, table1.customername, table1.jobid, table2.location, table2.[key]
from table1
inner join table2
on table1.id= RIGHT([table2].[key],7)"
So changing it to a left join:
This does not work:
$query = "select distinct table1.id, table1.customername, table1.jobid, table2.location, table2.[key]
from table1
left join table2
on table1.id = RIGHT([table2].[key],7)"
It does not return any of the table2 data. Any advice on what I am doing wrong would be very welcome.
Thanks in advance.
I put together a SQL Fiddle to show that your query should work (based on a guess about datatypes). Given that you've wrapped your queries as strings, that raises the question of whether your problem is actually with SQL, or if the ODBC (or whatever) connection is actually returning a parser error rather than a result set. Have you looked at what the db is providing in return? Have you ensured that there is whitespace between each word, even for line breaks (copying your text as-is shows CRs and LFs, but check your code); otherwise, it's quite possible that you're sending SQL Server something like "SELECT * FROMTABLEWHERETHING" rather than "SELECT * FROM TABLE WHERE".
Thank you all for your input. For some reason the RIGHT was not returning anything so I managed to resolve with :
left JOIN [table2] ON [table1].id= substring([key],(CHARINDEX ('#',[key] , 1)+1),7)
Thanks for all your responses.
Jim

BigQuery - joining on a repeated field

I'm trying to run a join on a repeated field.
Originally I get an error:
Cannot join on repeated field payload.pages.action
I fix this by running flatten on the relevant table (this is only an example query - it will give empty result if it would successfully run):
SELECT
t1.repository.forks
FROM publicdata:samples.github_nested t1
left join each flatten(publicdata:samples.github_nested,payload.pages) t2
on t2.payload.pages.action=t1.repository.url
I get a different error:
Table wildcard function 'FLATTEN' can only appear in FROM clauses
This used to work in the past. Is there some syntax change?
I don't think there has been a syntax change, but you should be able to wrap the flatten statement in a subselect. That is,
SELECT
t1.repository.forks
FROM publicdata:samples.github_nested t1
left join each (SELECT * FROM flatten(publicdata:samples.github_nested,payload.pages)) t2
on t2.payload.pages.action=t1.repository.url

SQL Left Outer Join causes Msg 4145 (non-boolean where boolean expected)

I'm new here so if I do something that breaks convention please let me know.
I am trying to create a simple query that includes a single outer join before I move onto a larger and more complicated query. When I run my query before adding the join it works as expected. When I add the join the query returns an error message. I cannot determine the cause of the error. I am working in Microsoft SQL Server 2008 R2.
This query runs successfully and produces the expected results:
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1,
table2
where table1.id_num = table2.id_num
This query does not run successfully:
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1,
table2
where table1 left outer join table2 on table1.id_num = table2.id_num
The error message I get is:
Msg 4145, Level 15, State 1, Line 6
An expression of non-boolean type specified in a context where a condition is expected, near 'left'.
I also tried "outer join" instead of "left outer join", but this produced a similar error message (the only difference was "near 'outer'" instead of "near 'left'").
I do know what boolean means but I am not sure why it's an issue here. The boolean operator comes later in the same line. My code looks like it follows the same format as other code I have seen. Any assistance would be appreciated.
your join needs to be after the FROM not in the WHERE clause
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1
left outer join table2 on table1.id_num = table2.id_num
You are using deprecated syntax, listing out tables and defining their relationship in the WHERE clause has been replaced by explicit JOIN statements
FROM Table1 t1
JOIN Table2 t2
ON t1.col1 = t2.col1
LEFT JOIN Table3 t3
ON t1.col2 = t3.col1
Old style joins do allow for outer joins:
use MyDatabase
select table1.ID_NUM,
table1.LAST_NAME
From table1,table2
where table1.id_num *= table2.id_num
This old syntax should be avoided, but helpful to know what they are if you come across them.

SQL Syntax JOIN google bigquery

I am getting this error in Google BigQuery:
Error: Ambiguous field reference in SELECT clause. (Remember to fully qualify all field names in the SELECT clause as <table.field>.)
My query is
SELECT LoanPerf1.loankey, Loans.Key
FROM prosperloans1.LoanPerf1
JOIN prosperloans1.Loans
ON LoanPerf1.loankey = Loans.Key
prosperloans1 is the dataset id
the 2 table names are correct.
the error returns regardless of which field name appears first in the select clause.
The documentation on Google SQL Syntax says this is correct:
// Simple JOIN of two tables
SELECT table1.id, table2.username
FROM table1
JOIN table2
ON table1.name = table2.name AND table1.id = table2.customer_id;
Thanks
Shawn
Try adding an AS clause to the table names:
SELECT LoanPerf1.loankey, Loans.Key
FROM prosperloans1.LoanPerf1 as LoanPerf1
JOIN prosperloans1.Loans as Loans
ON LoanPerf1.loankey = Loans.Key