The two tables are quite large and my select statement has more values than I get, but I think I can simplify this data and query in order to answer my question.
This is my select statement:
SELECT invoice.InvoiceNum, Layer, InvoiceItemNum FROM (INVOICE left outer join InvoiceItem item ON item.InvoiceNum = Invoice.InvoiceNum ) ORDER BY invoice.InvoiceNum
So I have two tables. Invoice table and InvoiceItem table. They are joined by the InvoiceNum column in each table and display the InvoiceNum and Layer columns
The following are the results of this query:
InvoiceNum | Layer | InvoiceItemNum 1 | 10 | 1 1 | 0 | 2 1 | 7 | 3 1 | 0 | 4 2 | 0 | 1 2 | 3 | 2 3 | 0 | 1 3 | 0 | 2 3 | 0 | 3 4 | 0 | 1 4 | 0 | 2 4 | 5 | 3
Since my InvoiceItem table has multiple rows that can be assigned to 1 InvoiceNum, this results in duplicate InvoiceNums in my results, which I don't want.
This is the result I am trying to get, to list only 1 invoice number from the invoice table, where the first case is a non-zero value from the layer column of the InvoiceItem table, and if there is no non-zero value, list The first zero.
Try something like this:
InvoiceNum | Layer | InvoiceItemNum 1 | 10 | 1 2 | 3 | 2 3 | 0 | 1 4 | 5 | 3
I'm just not sure how to do this, or if it's even possible given that they are on two different tables.
Assumption/Understanding:
sybase
, the question does not differentiate between the 4x different Sybase RDBMS products (ASE
,SQLAnywhere
,IQ
,Advantage
), so I'll stick with common SQL syntax (i.e. 4x products have different SQL dialects; also, ASE doesn't support CTE)left (outer) join
as the output provided does not seem to indicate that there are any "missing" rows inInvoiceItem
Layer
andInvoiceItemNum
columns belong to, so I'm assuming they belong toInvoiceItem
Guess a set of minimal table definitions and associated
insert
statements:Query that generates OP’s current output:
A few different (complex, confusing) ideas for generating the output the OP needs:
left (external) join
ASE 16.0
This question is a bit tricky:
Try it in Postgres:
Demo
In MySQL 8:
Try this: