postgresql query year (integer) field equals year of current date - postgresql

This seems like it should be fairly simple and straight forward but I haven't yet found the right combination. I have a column called last_assess_yr that is an integer. I am trying to find all rows from my_table where '01-01' + 'year' < current_date and give them a value in a new column. I have the following:
SELECT last_assess_yr,
CASE
WHEN format('01-01-%s'::text, last_assess_yr)::timestamp without time
zone < current_date
THEN YES
ELSE NO
END AS assess_value
FROM my__table
but, the results are not correct

You don't actually need to convert the integer into a timestamp, you could just compare the extracted year to the integer.
select
case when last_assess_yr < extract('year' from current_date)::int
then 'YES' else 'NO'
end
However for reference the following will work:
select
case when format('01-01-%s'::text, 2017)::timestamp < current_date
then 'YES' else 'NO'
end
i.e. you do not need to remove time (of day) when you convert a string of '01-01-2017' to a timestamp.
and: I assume YES and NO also need to be treated as literals: 'YES' and 'NO'

In case someone else is looking, this worked for me:
WHEN last_assess_yr > 0 AND format('%s-05-05'::text, w.last_assess_yr)::timestamp <
current_date THEN 'yes'
ELSE 'no'
END

Related

looking to create dynamic date buckets in tableau

I am looking to create the table below, trying to figure out the if statement with dates and buckets and need assistance. note the dates I have do not include days, just mm/yy.
Make a date field by string concatenation to add in a day value.
date('01/'+[your_mm/yyyy_field])
Then create a date bucket field with the newly created [date] calc and comparing to today's date.
if datediff('month',[date],TODAY()) > 1 then 'In past'
elseif datediff('month',[date],TODAY()) = 1 then 'Last Month'
elseif datediff('month',[date],TODAY()) = 0 then 'Current Month'
elseif datediff('month',[date],TODAY()) = -1 then 'Next Month'
else 'Future'
end

How to find out Number of Workdays between two dates in HANA?

How to find out Number of Workdays(Monday to Friday) between two dates in SAP HANA ? We do not have to consider holidays.
We cant use WORKDAYS_BETWEEN() as we do not have TFACS table.
Here is how you can so ist in sql:
Calculate the number of whole weeks, multiply by 5
Add the remaining days: subtract weekday start date from weekday end date, correct for weekends (least...), Correct for carry-over (+5)
The second part can be simplified a little so that you don't have to write the subtraction twice.
Here an example with start date '2015-12-04' and end date '2015-12-19):
SELECT ROUND( DAYS_BETWEEN (TO_DATE ('2015-12-04', 'YYYY-MM-DD'), TO_DATE('2015-12-19', 'YYYY-MM-DD')) / 7, 0, ROUND_DOWN) * 5
+ ( case
when WEEKDAY (TO_DATE('2015-12-19', 'YYYY-MM-DD') ) - WEEKDAY (TO_DATE('2015-12-04', 'YYYY-MM-DD')) >= 0
then least( WEEKDAY (TO_DATE('2015-12-19', 'YYYY-MM-DD')), 5) - least( WEEKDAY (TO_DATE('2015-12-04', 'YYYY-MM-DD')), 5)
else
least( WEEKDAY (TO_DATE('2015-12-19', 'YYYY-MM-DD')), 5) - least( WEEKDAY (TO_DATE('2015-12-04', 'YYYY-MM-DD')), 5) + 5
end )
"Workdays" FROM DUMMY;
--> 11
I preferred to create a user defined function here to use in HANA SQLScript codes as follows
Create Function CalculateWorkDays (startdate date, enddate date)
returns cnt integer
LANGUAGE SQLSCRIPT AS
begin
declare i int;
cnt := 0;
i := 0;
while :i <= days_between(:startdate, :enddate)
do
if WEEKDAY( ADD_DAYS(:startdate,:i) ) < 5
then
cnt := :cnt + 1;
end if;
i := :i + 1;
end while;
end;
Please note that the above code block seems to contain an unnecessary loop.
On the other hand, if you have additional tables like department holidays, or personal holidays, etc. It might be useful to check these tables in the WHILE loop. Please refer to following SQL tutorial Calculate the Count of Working Days Between Two Dates where I created a similar SQL function checking custom work calendars or holiday calendars.
Here is how you call the function as sample
select CalculateWorkDays('20170101', '20170131') as i from dummy;
I hope it helps,

TSQL order by / convert with compare operator

I would like to have a construction like this:
... order by ([datetimefield-1] > getdate() AS MyBoolean) desc, [field-2]
So all dates that are > now should be first in the order BUT it should not ordered by the date itself, because there ist a second column which will give the final oder. The datetimefield-1 should be True if it is in the future and false if not (or if it is NULL). And this true or false should then the value to preorder it so that all records where the date is in the future are on top.
The syntax here is wrong, but I guess it is possible with the right.
Thanks for any help.
order by case
when datetimefield > dateadd(day, 1, getdate())
then 0
else 1
end,
YourOtherColumn

T-sql IF Condition date evaluation

I have a simple question regarding T-SQL. I have a stored procedure which calls a Function which returns a date. I want to use an IF condition to compare todays date with the Functions returned date. IF true to return data.
Any ideas on the best way to handle this. I am learning t-sql at the moment and I am more familar with logical conditions from using C#.
ALTER FUNCTION [dbo].[monday_new_period](#p_date as datetime) -- Parameter to find current date
RETURNS datetime
BEGIN
-- 1 find the year and period given the current date
-- create parameters to store period and year of given date
declare #p_date_period int, #p_date_period_year int
-- assign the values to the period and year parameters
select
#p_date_period=period,
#p_date_period_year = [year]
from client_week_uk where #p_date between start_dt and end_dt
-- 2 determine the first monday given the period and year, by adding days to the first day of the period
-- this only works on the assumption a period lasts a least one week
-- create parameter to store the first day of the period
declare #p_start_date_for_period_x datetime
select #p_start_date_for_period_x = min(start_dt)
from client_week_uk where period = #p_date_period and [year] = #p_date_period_year
-- create parameter to store result
declare #p_result datetime
-- add x days to the first day to get a monday
select #p_result = dateadd(d,
case datename(dw, #p_start_date_for_period_x)
when 'Monday' then 0
when 'Tuesday' then 6
when 'Wednesday' then 5
when 'Thursday' then 4
when 'Friday' then 3
when 'Saturday' then 2
when 'Sunday' then 1 end,
#p_start_date_for_period_x)
Return #p_result
END
ALTER PROCEDURE [dbo].[usp_data_to_retrieve]
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF monday_new_period(dbo.trimdate(getutcdate()) = getutcdate()
BEGIN
-- SQL GOES HERE --
END
Thanks!!
I assume you are working on Sql2008. See documentation of IF and CASE keywords for more details.
CREATE FUNCTION dbo.GetSomeDate()
RETURNS datetime
AS
BEGIN
RETURN '2012-03-05 13:12:14'
END
GO
IF CAST(GETDATE() AS DATE) = CAST(dbo.GetSomeDate() AS DATE)
BEGIN
PRINT 'The same date'
END
ELSE
BEGIN
PRINT 'Different dates'
END
-- in the select query
SELECT CASE WHEN CAST(GETDATE() AS DATE) = CAST(dbo.GetSomeDate() AS DATE) THEN 1 ELSE 0 END AS IsTheSame
This is the basic syntax for a T-SQL IF and a date compare.
If you are comparing just the date portion for equality you will need to use:
select dateadd(dd,0, datediff(dd,0, getDate()))
This snippet will effectively set the time portion to 00:00:00 so you can compare just dates. So in use it will look something like this.
IF dateadd(dd,0, datediff(dd,0, fn_yourFunction())) = dateadd(dd,0, datediff(dd,0, GETDATE()))
BEGIN
RETURN SELECT * FROM SOMEDATA
END
Hope that helps!

Unable to convert from Julian INT date to regular TSQL Datetime

Help me Stackoverflow, I'm close to going all "HULK SMASH" on my keyboard over this issue. I have researched carefully but I'm obviously not getting something right.
I am working with a Julian dates referenced from a proprietary tool (Platinum SQL?), though I'm working in SQL 2005. I can convert their "special" version of Julian into datetime when I run a select statement. Unfortunately it will not insert into a datetime column, I get the following error when I try:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
So I can't setup datetime criteria for running a report off of the Stored Procedure.
Original Value: 733416
Equivalent Calendar Value: 01-09-2009
Below is my code... I'm so close but I can't quite see what's wrong, I need my convert statement to actually convert the Julian value (733416) into a compatible TSQL DATETIME value.
SELECT
org_id,
CASE WHEN date_applied = 0 THEN '00-00-00'
ELSE convert(char(50),dateadd(day,date_applied-729960,convert(datetime, '07-25-99')),101)
END AS date_applied,
CASE WHEN date_posted = 0 THEN '00-00-00'
ELSE convert(char(50),dateadd(day,date_posted-729960,convert(datetime, '07-25-99')),101)
END AS date_posted
from general_vw
SELECT
org_id,
CASE WHEN date_applied = 0 OR date_applied < 639906 THEN convert(datetime, '1753-01-01')
ELSE dateadd(day,date_applied-729960,convert(datetime, '07-25-99'))
END AS date_applied,
CASE WHEN date_posted = 0 OR date_applied < 639906 THEN convert(datetime, '1753-01-01')
ELSE dateadd(day,date_posted-729960,convert(datetime, '07-25-99'))
END AS date_posted
from general_vw
You're casting to char but want a datetime so that's one easy fix.
You were also using '00-00-00' as your minimum date, but the minimum TSQL date is '1753-01-01'. Alternatively you could use something like ('1900-01-01') but that would need a change to the "less than" date_applied comparer.
I've added a "less than" date_applied comparer too. I calculated this as "SELECT 729960 + datediff(day,convert(datetime, '07-25-99'), convert(datetime,'1753-01-01'))". Any number less than this would cause a date underflow.