• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 237
  • Last Modified:

Converting Excel formula to SQL Case II

I would like to ask again for your help converting an excel formula to sql syntax.

the excel formula goes as follows:
Remaining Contract Length: 

=IF(SalesOrderTypeCode="Blanket", ContractEndDate-IF(TodaysDate > ContractStartDate,IF(TodaysDate>ContractEndDate, ContractEndDate, TodaysDate),ContractStartDate)+1, 0)

Open in new window


I got help originally to convert the formula, but more logic was added to it this I need more help.

I currently have the formula in sql like this:

,	RemainingContractLength =
	CASE 
	        WHEN SalesOrderLineTypeCode = 'BLANKET' 
		THEN DATEDIFF(dd, @Today, ContractEndDate) + 1 
		ELSE 0 
	END

Open in new window


Thank you very much for your help.
0
metropia
Asked:
metropia
  • 3
  • 2
1 Solution
 
c1nmoCommented:
You can nest, not tested but something like:

CASE
WHEN SalesOrderTypeCode="Blanket"
THEN DATEDIFF(dd, ContractEndDate,
      CASE WHEN TodaysDate > ContractStartDate THEN
            CASE WHEN TodaysDate>ContractEndDate THEN ContractEndDate ELSE TodaysDate END
      ELSE ContractStartDate END) + 1 ELSE 0 END
0
 
metropiaAuthor Commented:
thank you.

somehow the number of days is not coming up the same when i run it on sql server.

i am attaching the excel file, if you notice, for row 13, the number on column Remaining Contract Length if 214, but in sql server comes back as 212

I am also attaching sample data from sql server
Sales-Order-Proration-Sample.xlsx
sample-data.txt
0
 
c1nmoCommented:
I get -295 using your sample data with:

CASE
WHEN SalesOrderTypeCode='Blanket'
THEN DATEDIFF(dd, ContractEndDate,
      CASE WHEN GETDATE() > ContractStartDate THEN
            CASE WHEN GETDATE()>ContractEndDate THEN ContractEndDate ELSE GETDATE() END
      ELSE ContractStartDate END) + 1 ELSE 0 END
0
 
c1nmoCommented:
214 for row 13 values now:

select CASE
WHEN SalesOrderTypeCode='Blanket'
THEN DATEDIFF(dd,
      CASE WHEN Today > ContractStartDate THEN
            CASE WHEN Today>ContractEndDate THEN ContractEndDate ELSE Today END
      ELSE ContractStartDate END, ContractEndDate) + 1 ELSE 0 END  from test
0
 
metropiaAuthor Commented:
excellent solution!
0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now