Home > Mobile >  SQL (Snowflake): Can I use a virtual column to make another virtual column? If not, what's the
SQL (Snowflake): Can I use a virtual column to make another virtual column? If not, what's the

Time:12-16

So, I have two columns which are in unix/ epoch format (in milliseconds). I convert them accordingly:

dateadd(S, TIME_START/1000, '1970-01-01') AS J_Start, 

dateadd(S, TIME_END/1000, '1970-01-01') AS J_End, 

I want another column with the differential. However, when I try and do J_Start - J_End, I get an invalid identifier error. Is there any way around this? I've also tried substracting the full conversion syntax from one another but to no avail...

I was thinking of creating a virtual table and then joining it to the original but I would still encounter the aforementioned problem: Generating a virtual column from other, pre-existing one(s)

CodePudding user response:

You can use datediff to get the differential. I am calculating the diff in days but you can change it as desired. Double quotes wasn't the cause of the error, but you don't really need them. Just use column names that don't collide with reserved keywords.

select datediff(day, dateadd(S, j_start/1000, '1970-01-01'),dateadd(S, j_end/1000, '1970-01-01'))

You could also use simple subtraction, but you'd have to cast the output of dateadd as date first. The one above is easier to maintain and modify though

select dateadd(S, j_start/1000, '1970-01-01')::date - dateadd(S, j_end/1000, '1970-01-01')::date

And if you really want to re-use column alias in the same select, which I am not a fan of, you can do

select dateadd(S, j_start/1000, '1970-01-01')::date as j_start,
       dateadd(S, j_end/1000, '1970-01-01')::date as j_end,
       b-a as diff_days

Having said that, if you only need the diff between two dates expressed in milliseconds, it doesn't matter if you use 1970 or 1800. Just do

select floor((time_end-time_start) / (1000 * 60 * 60 * 24)) as diff_days

CodePudding user response:

It works for me:

select 5 as a, 1 as b, a-b as c;
 --- --- --- 
| A | B | C |
|--- --- ---|
| 5 | 1 | 4 |
 --- --- --- 

Unless I did not fully understand the question.

If you have your full query with exact error message, it can help.

CodePudding user response:

in snowflake you can reference the named object of the SELECT section in the other sections, and the parse most "gets what you mean", thus in snowflake:

SELECT 
     '2021-12-16' AS date_string,
     to_date(date_string) as datetime_a,
     dateadd('day', 1, date_time_a) AS a_day_later,
     date_diff('hours', datetime_a, a_day_later);

is just fine, and will give the results of:

"2021-12-16", 2021-12-16, 2021-12-17, 24

thus in the SQL I gave you on your location question, I was refering to things just declared.

The error you are seeing is the fact the subtraction of date's is not supported, because what format do you want the answer in? Thus the use of date_diff

  • Related