Postgresql
如何查找序列中缺失的值?
我想從我的表中的一系列值中找到缺失的行。例如,在這張照片
documentno
'YD4BC2006008'
中是缺失的。我想通過
c_order_id
和找到缺失的行documentno
。我試過了,但沒有返回預期的結果:
select * from (SELECT distinct c_order_id, documentno,cast(right(documentno,3) as integer) as no FROM adempiere.c_order ORDER BY documentno, c_order_id) as f
在此範例中,缺少許多行: from
'DGPOS2003030'
到'DGPOS2003068'
。如何編寫查詢來檢索它們?
一種更動態的方法是,獲取最低的 Number 和最高的 Number,然後從那裡建構缺少的 m。
如果您沒有範例 2006004 中的前導 2,則需要填充生成的部分
CREATE TABLE documents ( "order_id" VARCHAR(22), "documentno" VARCHAR(12) ); INSERT INTO documents ("order_id", "documentno") VALUES ('100001110', 'VD4BC2006004'), ('100001114' ,'VD4BC2006005'), ('100001135' ,'YD4BC2006006'), ('100001166' ,'YD4BC2006007'), ('100001215' ,'YD4BC2006009'), ('100001256' ,'YD4BC2006010'), ('100001289' ,'YD4BC2006011'), ('100001332' ,'VD4BC2006013'), ('100001334' ,'VD4BC2006014'), ('100001432' ,'VD4BC2006015'), ('100000616' ,'DGP0S2003028'), ('100000617' ,'DGP0S2003029'), ('100001034' ,'DGP0S2003069');
WITH cte as ( SELECT LEFT("documentno",5) lpart , MIN(RIGHT("documentno",7)) minpart, MaX(RIGHT("documentno",7)) maxpart FROM documents groUP BY LEFT("documentno",5)) sELECT lpart || generate_series(minpart::INTEGER, maxpart::INTEGER) as mdocumentno FROM cte except select documentno from documents ORDER bY mdocumentno;
| 文件號 | | :----------- | | DGP0S2003030 | | DGP0S2003031 | | DGP0S2003032 | | DGP0S2003033 | | DGP0S2003034 | | DGP0S2003035 | | DGP0S2003036 | | DGP0S2003037 | | DGP0S2003038 | | DGP0S2003039 | | DGP0S2003040 | | DGP0S2003041 | | DGP0S2003042 | | DGP0S2003043 | | DGP0S2003044 | | DGP0S2003045 | | DGP0S2003046 | | DGP0S2003047 | | DGP0S2003048 | | DGP0S2003049 | | DGP0S2003050 | | DGP0S2003051 | | DGP0S2003052 | | DGP0S2003053 | | DGP0S2003054 | | DGP0S2003055 | | DGP0S2003056 | | DGP0S2003057 | | DGP0S2003058 | | DGP0S2003059 | | DGP0S2003060 | | DGP0S2003061 | | DGP0S2003062 | | DGP0S2003063 | | DGP0S2003064 | | DGP0S2003065 | | DGP0S2003066 | | DGP0S2003067 | | DGP0S2003068 | | VD4BC2006006 | | VD4BC2006007 | | VD4BC2006008 | | VD4BC2006009 | | VD4BC2006010 | | VD4BC2006011 | | VD4BC2006012 | | YD4BC2006008 |
db<>在這裡擺弄