【问题标题】:sql create sequence number in subset - apache derbysql 在子集中创建序列号 - apache derby
【发布时间】:2020-07-15 20:39:04
【问题描述】:

能够使用以下查询生成序列号

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

这给出了结果

要求以Transaction和HSN为例生成序列号

有什么办法可以得出这个结果。使用 derby-10.13.1.1

【问题讨论】:

标签: sql derby window-functions


【解决方案1】:

Derby 似乎不完全支持标准窗口函数row_number()

模拟这一点的典型方法是使用子查询来计算有多少行具有相同的transaction_id 和较小的hsn,如下所示:

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

请注意,如果有重复的 (transaction_id, hsn) 元组,它们将得到相同的 seqno。这类似于窗口函数rank() 的工作方式。如果你想要一个唯一的数字,那么你可以尝试添加另一个随机排序条件:

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

【讨论】:

  • @vels4j:我用不使用窗口函数的解决方案更新了我的答案。
  • 没用,感谢您的努力,我将与您分享一个 sql fiddle。用 derby 寻找一些在线工具
  • @vels4j:没用是什么意思?你得到一个错误(哪个)?或者可能是错误的结果?
  • @vels4j:这似乎与您想要的非常接近。我刚刚在查询中添加了一个order by 子句。
  • 不走运 TRANSACTION_ID HSN SEQNO CS610-20-10003 3004 1 CS610-20-10003 3004 1 CS610-20-10003 3304 3 CS610-20-10003 3401 4
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
相关资源
最近更新 更多