Able to generate Sequence number using the following query
CREATE SEQUENCE seqno AS integer
START WITH 1;
SELECT t1.*,
(NEXT VALUE
FOR seqno) AS seqno
FROM
(SELECT l.TRANSACTION_ID,
l.HSN
FROM RWLINEITEM l
WHERE l.TRANSACTION_ID IN ('CS610-20-10003','CS610-20-10002')
GROUP BY l.TRANSACTION_ID,l.HSN) t1
this gives result
The requirement is to generate sequence number by Transaction and HSN for example
Is there any way to arrive this result. Using derby-10.13.1.1
The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.
CREATE SEQUENCE order_id; The following statement creates a sequence of type BIGINT with a start value of 3,000,000,000. The value increases by 1, and the last legal value is the largest possible BIGINT. If NEXT VALUE FOR is invoked on the generator again, Derby throws an exception.
Derby is based on the Java, JDBC, and SQL standards. Derby provides an embedded JDBC driver that lets you embed Derby in any Java-based solution. Derby also supports the more familiar client/server mode with the Derby Network Client JDBC driver and Derby Network Server.
It seems like Derby does not fully support standard window function row_number()
.
A typical approach to emulate this is to use a subquery that counts how many rows have the same transaction_id
and a smaller hsn
, like so:
select
transaction_id,
hsn,
1 + coalesce(
(
select count(*)
from rwlineitem l1
where l1.transaction_id = l.transaction_id and l1.hsn < l.hsn
),
0
) seqno
from rwlineitem l
where transaction_id in ('CS610-20-10003','CS610-20-10002')
order by transaction_id, hsn
Note that if there are duplicates (transaction_id, hsn)
tuples, they would get the same seqno
. This is similar to how window function rank()
works. If you want a unique number, then you can try and add another random sorting criteria:
select
transaction_id,
hsn,
1 + coalesce(
(
select count(*)
from rwlineitem l1
where
l1.transaction_id = l.transaction_id
and (
l1.hsn < l.hsn
or (l1.hsn = l.hsn and random() < 0.5)
)
),
0
) seqno
from rwlineitem l
where transaction_id in ('CS610-20-10003','CS610-20-10002')
order by transaction_id, hsn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With