2016-03-29 37 views
-1

我有這樣

enter image description here 中值的N個NUM
一個表有這樣我怎麼能找到失蹤相同的格式ExciseInvoiceNo,鑑於我怎麼能從表中找到缺失值?

DECLARE @temp table 
(val int) 
insert INTO @temp([val]) 
SELECT CONVERT(INT, (case when CHARINDEX('/', EXCISEINVOICENO) > 0 Then 
       cast(substring(EXCISEINVOICENO,1,len(EXCISEINVOICENO) - 3) as int) 
      else Cast(EXCISEINVOICENO as Int) end) ) as ExciseInvoiceIndex 
FROM tblExciseInvoice 
WHERE  CompYearID=109 
    AND (InvoiceDate BETWEEN '10/1/2015 12:00:00 AM' AND '03/30/2016 11:59:59 PM') 
select (select isnull(max(val)+1,1) from @temp where val < md.val) as [from], 
    md.val - 1 as [to] 
from @temp md 
    where md.val != 1 and not exists (
     select 1 from @temp md2 where md2.val = md.val - 1) 

我試圖這一點,但在適當的沒有得到結果Formate

+0

請編輯我們的問題,並提供樣品數據和預期結果。正如所寫的,你的問題太模棱兩可了。 –

+0

附上樣品桌請點擊圖片 – Ritesh

+1

您可以使用[此工具](https://ozh.github.io/ascii-tables/)創建漂亮的桌子。 – robsn

回答

0

假設您錯過了從發票的第一次發生到最大發票發生的意思。缺失的是之間的任何...

也許你的發票開始在1/15或somethign,然後我們需要LPAD零4個職位。或包含很多可以上去......

Working SQL FIDDLE

這裏有一個方法

  1. 將表與自身
  2. 但使用加入的+1標準上的左部發票號碼
  3. 並確保正確的零件匹配。

這種方法vs超前/滯後窗函數的缺點是它不能使用索引,因爲我們正在操縱字符串,因此它可能在大型數據集上很慢。 。

SELECT A.ExciseInvoiceNO, B.ExciseInvoiceNo, 
case when B.ExciseInvoiceNo is null then 
cast(left(A.ExciseInvoiceNO,4)+1 as varchar(20)) + right(A.ExciseInvoiceNO,3) end 
as MissingInvoices 
FROM foo A 
LEFT JOIN Foo B 
on Left(A.ExciseInvoiceNO,4)+1 = left(B.ExciseInvoiceNO,4) 
and right(A.ExciseInvoiceNO,3) = right(B.ExciseInvoiceNO,3) 
WHERE case when B.ExciseInvoiceNo is null then 
cast(left(A.ExciseInvoiceNO,4)+1 as varchar(20)) + right(A.ExciseInvoiceNO,3) end is not null 
使用

的做法窗口功能

2nd Working Fiddle

這個窗口功能讓你看看通過exciseInvoiceNo訂購的下一個記錄,然後比較結果。我們可能必須先將右邊的3個字符再分配給左邊,但是卻不理解您的InvoiceNumber格式的性質,我不能確定。我使用CTE(公用表表達式)將下一個記錄發票號碼的值存儲在一個數據集中,然後我們使用字符串操作。

with cte as (
Select ExciseInvoiceNO Ino, 
Lead(ExciseInvoiceNo,1) over (order by ExciseInvoiceNo) compare 
from foo A) 

Select case when left(INo,4)+1 = left(compare,4) 
      and right(Ino,3) = right(compare,3) 
     then Null 
     else cast(left(INo,4)+1 as varchar(20)) + right(Compare,3) 
     end as MissingInvoiceNo 
from cte 
WHERE case when left(INo,4)+1 = left(compare,4) 
      and right(Ino,3) = right(compare,3) 
     then Null 
     else cast(left(INo,4)+1 as varchar(20)) + right(Compare,3) end 
    is not null 
+0

Thnx爲您的答覆,但它不工作 – Ritesh

+0

小提琴的作品...所以它不能工作?您的發票長度是否超過7? 4+/+ 2?簡而言之,除非我明確知道什麼不起作用,否則我無法改進。可能任何一邊的長度都可能是任意大小。如果是這樣,我們需要根據/分成不同的值並比較... – xQbert

+0

更好地定義您的發票號碼的性質嗎?他們都有什麼/?s 15是什麼意思是發票#1023/15與1023相同/ 14?如果我有1023/14和1023/16是15失蹤,什麼決定「失蹤」?如果我有1023/14和1025/14是1024/14失蹤?根據您的示例,您正在評估/ /的左邊的所有內容,以確定是否缺少某些內容... – xQbert