2016-07-20 95 views
1

我需要一個SQL查詢,它允許我顯示剩餘多少天來處理髮票,此查詢應指示剩餘時間以在自動取消之前授權報價,即14天對於未處理的和7天的部分處理。計算在SQL Server中剩餘使用的天數

任何人都可以幫我嗎?

例如,如果今天有報價,它應該顯示14天,明天13天等。

+1

初始日期,我認爲你正在尋找爲'datediff()' – HoneyBadger

+0

@HoneyBadger你能告訴我我將如何完成這一點,我是新的SQL語言 –

回答

0

您沒有提供數據,因此這裏是基於虛擬數據的示例。正如在評論中提到的,您需要使用DATEDIFF函數。但在找出日期之間的日期之前,您應該在DATEADD函數的幫助下將14添加到發票日期。這會給你倒計時效果,你需要:

;WITH invoices AS (
SELECT 1 as invoice_num, 
     '2016-07-10' as invoice_date, 
     1 as invoice_status 
UNION ALL 
SELECT 2, 
     '2016-07-01', 
     1 
UNION ALL 
SELECT 3, 
     '2016-07-12', 
     2 
UNION ALL 
SELECT 4, 
     '2016-07-18', 
     2 
), invoice_statuses AS (
SELECT 1 as invoice_status, 
     'un-processed' as status_description 
UNION ALL 
SELECT 2, 
     'partially processed' 
) 


SELECT i.invoice_num, 
     i.invoice_date, 
     s.status_description, 
     DATEDIFF(day,GETDATE(),DATEADD(day, 
      CASE WHEN i.invoice_status = 1 THEN 14 
       WHEN i.invoice_status = 2 THEN 7 
       ELSE 0 END 
          ,i.invoice_date)) as days_left 
FROM invoices i 
LEFT JOIN invoice_statuses s 
    ON s.invoice_status = i.invoice_status 

輸出將是:

invoice_num invoice_date status_description days_left 
1   2016-07-10  un-processed  4 
2   2016-07-01  un-processed  -5 
3   2016-07-12  partially processed -1 
4   2016-07-18  partially processed 5 

如果更改GETDATE()2016-07-21輸出將是:

invoice_num invoice_date status_description days_left 
1   2016-07-10  un-processed  3 
2   2016-07-01  un-processed  -6 
3   2016-07-12  partially processed -2 
4   2016-07-18  partially processed 4 
0

正如提到的評論,這可以很容易地使用DATEDIFF功能實現:

DECLARE @InvoiceDate DATE = '2016-08-01'; 
SELECT DATEDIFF(DAY, GETDATE(), @InvoiceDate); 
0

,讓您的取消日期,您需要與其餘7或14天(視情況)

這裏有一個例子

declare @datStart as date = '2016-07-15'; --an initial start date 
declare @proc as nvarchar(1) = 'U'; --unprocessed 

--this would give a final process ing date 
SELECT case when @proc ='U' THEN DATEADD(DAY, 14, @datStart) ELSE DATEADD(DAY, 7, @datStart) END 

--this gives you days unil the delete date 
SELECT datediff(day,getdate(), case when @proc ='U' THEN DATEADD(DAY, 14, @datStart) ELSE DATEADD(DAY, 7, @datStart) END)