我需要一个SQL查询,允许我显示处理发票的剩余天数,此查询应指明在自动取消之前授权报价的剩余时间,即未处理的7天和7天用于部分处理。
任何人都可以帮助我吗?
EG。如果今天有报价,它应该显示14天,明天13天等。
答案 0 :(得分: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
答案 1 :(得分:0)
正如评论中所提到的,使用DATEDIFF
函数可以轻松实现这一点:
DECLARE @InvoiceDate DATE = '2016-08-01';
SELECT DATEDIFF(DAY, GETDATE(), @InvoiceDate);
答案 2 :(得分: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)