How to get Day difference between two dates in snowflake - snowflake-cloud-data-platform

How to get difference betwen these below two dates in snowflake.
select datediff(
day,
Date('Tue Jan 01 1980 00:00:00 GMT-0800 (Pacific Standard Time)')::timestamp,
Date('Tue Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)')::timestamp
);

I think the time stamp format is not valid, and the time zone name seems unnecessary and hard to parse.
I wrote a small function to take the first 33 characters from the input and then convert it to a time stamp:
create or replace function to_convert_ts ( v varchar )
returns timestamp_tz
as
$$
select to_timestamp_tz( left(V,33), 'DY MON DD YYYY HH24:MI:SS GMTTZHTZM' )
$$;
select datediff( day, to_convert_ts( 'Tue Jan 01 1980 00:00:00 GMT-0800 (Pacific Standard Time)'),
to_convert_ts( 'Tue Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)' ) );
-- returns 14610

So as noted by Gokhan, this really is a date parsing problem. As can be seen by.
select
'Tue Jan 01 1980 00:00:00 GMT-0800 (Pacific Standard Time)' as date_str_a,
'Tue Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)' as date_str_b,
try_to_date(date_str_a) as date_a,
try_to_date(date_str_b) as date_b,
datediff(day, date_a, date_b ) as day_diff;
should show the date parse fails, the try_to_date versions return null if they fail, but the base problem can also be seen with:
select date('Tue Jan 01 1980 00:00:00 GMT-0800 (Pacific Standard Time)');
should give the very error your seeing.
Gokhan, shows how to write a function to do the trim in a hidden, which you can just used out in the open also.
[SUBSTR][1]
Thus
select
'Tue Jan 01 1980 00:00:00 GMT-0800 (Pacific Standard Time)' as date_str_a,
'Tue Jan 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)' as date_str_b,
to_timestamp_tz( left(V,33), date_str_a) as tz_a,
to_timestamp_tz( left(V,33), date_str_b) as tz_b,
datediff(day, tz_a, tz_b) as day_diff;

Related

how to convert month date in a text column into datetime

I have a table containing two columns like this:
Month_Date Year
Dec 31 2018
May 01 2020
Jun 05 2021
Jan 18 2022
Jul 19 2019
I hope to combine the Month_date and year in the same row and put it in a new column as a datetime format column. Could anyone help, please? I tried to convert the first column to a valid date, but failed because it doesn't show a complete month name.
You can try below approach.
Approach1:
select convert(datetime, [Month_Date] + ', ' + cast([Year] as varchar(4)), 107) from <TableName>
Approach2:
select cast(right(month_date,2)+'-'+left(month_date,3)+'-'+cast([Year] as varchar(4)) as date) from <TableName>

How to sort hours in SQL Server?

I have a table called Transaction. In that a column Time with TimeStamp datatype is found.
So the data will be looking like 2015-01-17 08:12:48.000
I want to display like 8 am
For example
`2015-01-17 08:12:48.000` `8 AM`
`2015-01-17 14:12:48.000` `2 PM`
now i got the result like above. This is my result
Hour
----
01 PM
02 PM
04 PM
05 PM
06 PM
07 AM
07 PM
08 AM
09 AM
10 AM
11 AM
12 PM
This is the query for above result.
SELECT
FORMAT(CAST(Time as datetime),'hh tt') hour,
COUNT(TransactionNumber) Total_Transaction,
SUM(Total) salesCost
FROM
[HQMatajer].[dbo].[Transaction]
WHERE
StoreID = '1001'
AND YEAR(Time) = '2015'
AND MONTH(Time) = '01'
AND DAY(Time) = '15'
GROUP BY
FORMAT(CAST(Time as datetime),'hh tt')`
Now I want to sort the hours. It should display like
07 AM
08 AM
09 AM
10 AM
11 AM
12 PM
01 PM
02 PM
.
.
07 PM
Thanks
Try adding this to the end of your statement:
, convert(varchar(2), [time], 8)
order by convert(varchar(2), [time], 8)
Resulting in this:
SELECT
FORMAT(CAST(Time as datetime),'hh tt') hour,
COUNT(TransactionNumber) Total_Transaction,
SUM(Total) salesCost
FROM
[HQMatajer].[dbo].[Transaction]
WHERE
StoreID = '1001'
AND YEAR(Time) = '2015'
AND MONTH(Time) = '01'
AND DAY(Time) = '15'
GROUP BY
FORMAT(CAST(Time as datetime),'hh tt')
, convert(varchar(2), [time], 8)
order by convert(varchar(2), [time], 8)
convert(varchar(2),[time],8) returns the datetime with style 8 in the following format: hh:mi:ss, and using varchar(2) truncates it to hh.
Documentation for convert and styles.
As Shakeer Mirza posted, using datepart() works as well.
Documentation for datepart.
Use DATEPART function simply
Select DATEPART(HH, YOUR_DATETIME_COL) AS HR, ......
........ --Write your Statements
........
ORDER BY HR
DATEPART will give result in integer format. So the Order by will give exact order

SQL Query to Calculate the Rolling Difference by Date

I cannot seem to work this one out to be exactly what need.
I'm using MS SQL Management Studio 2008.
I have a table (several actually) but lets keep it simple. The table contains daily stock figures for each item (SKU).
SKU DataDate Web_qty
2 2014-11-17 00:00:00 404
2 2014-11-18 00:00:00 373
2 2014-11-19 00:00:00 1350
66 2014-11-17 00:00:00 3624
66 2014-11-18 00:00:00 3576
66 2014-11-19 00:00:00 3570
67 2014-11-17 00:00:00 9353
67 2014-11-18 00:00:00 9297
67 2014-11-19 00:00:00 9250
I simply need the Select Query to return this:
SKU DataDate Difference
2 2014-11-17 00:00:00 ---
2 2014-11-18 00:00:00 -31
2 2014-11-19 00:00:00 +977
66 2014-11-17 00:00:00 ---
66 2014-11-18 00:00:00 -48
66 2014-11-19 00:00:00 -6
67 2014-11-17 00:00:00 ---
67 2014-11-18 00:00:00 -56
67 2014-11-19 00:00:00 -47
I do not need the --- parts, I have just shown that to draw attention to the fact that this one cannot be calculated as it is the first record.
I've tried using derived tables, but its getting a little confusing, i need to play with a working example so I can understand it better.
If someone could point me in the right direction I'm sure I'll be able to join the other tables back together (i.e. SKU Description and prices).
Really appreciate everyone's time
Kev
Try this. Use correlated sub-query to find rolling difference
CREATE TABLE #tem
(SKU INT,DataDate DATETIME,Web_qty INT)
INSERT #tem
VALUES( 2,'2014-11-17 00:00:00',404),
(2,'2014-11-18 00:00:00',373),
(2,'2014-11-19 00:00:00',1350),
(66,'2014-11-17 00:00:00',3624),
(66,'2014-11-18 00:00:00',3576),
(66,'2014-11-19 00:00:00',3570),
(67,'2014-11-17 00:00:00',9353),
(67,'2014-11-18 00:00:00',9297),
(67,'2014-11-19 00:00:00',9250)
SELECT *,
Web_qty - (SELECT Web_qty
FROM #tem a
WHERE a.sku = b.SKU
AND a.DataDate = Dateadd(dd, -1, b.DataDate)) Roll_diff
FROM #tem b
I know it is an old thread but I happened to have a similar problem and I ended up solving it with Window functions. It works in SQL 2014 but not sure about 2008.
It also solves the problem of potentially non-continuous data as well as rows with no changes. Hopefully it helps someone out there!
CREATE TABLE #tem
(SKU INT,DataDate DATETIME,Web_qty INT)
INSERT #tem
VALUES( 2,'2014-11-17 00:00:00',404),
(2,'2014-11-18 00:00:00',373),
(2,'2014-11-19 00:00:00',1350),
(2,'2014-11-20 00:00:00',1350),
(2,'2014-11-21 00:00:00',1350),
(66,'2014-11-17 00:00:00',3624),
(66,'2014-11-18 00:00:00',3576),
(66,'2014-11-19 00:00:00',3570),
(66,'2014-11-20 00:00:00',3590),
(66,'2014-11-21 00:00:00',3578),
(67,'2014-11-17 00:00:00',9353),
(67,'2014-11-18 00:00:00',9297),
(67,'2014-11-19 00:00:00',9250),
(67,'2014-11-20 00:00:00',9250),
(67,'2014-11-21 00:00:00',9240)
;WITH A AS (
SELECT
SKU,
DataDate,
Web_Qty,
Web_qty - LAG(Web_qty,1, 0)
OVER (PARTITION BY SKU ORDER BY DataDate) Roll_diff
FROM #tem b
)
SELECT
SKU,
DataDate ValidFromDate,
Lead(DataDate, 1, DateFromParts(9999,12,31)) OVER (PARTITION BY SKU ORDER BY DataDate) ValidToDate,
Web_Qty
FROM A WHERE Roll_diff <> 0

Format date to include day of week

I have a SQL Server 2012 query that converts date to VARCHAR
SELECT
CONVERT(VARCHAR(12), dbo.Download.Date_of_Download, 107) as Date_to_Display,
dbo.Download.Number_of_Computers
FROM dbo.Download
ORDER BY dbo.Download.Date_of_Download DESC
Below are results
Date_to_Display Number_of_Computers
-----------------------------------
Aug 14, 2014 240
Aug 13, 2014 519
Aug 12, 2014 622
Aug 11, 2014 2132
Aug 10, 2014 1255
Aug 09, 2014 3240
How do I include day of week, i.e. Saturday, Aug 09, 2014 ?
try this:
select datename(dw,getdate())
output:
------------------------------
Thursday
(1 row(s) affected)
using your query:
SELECT
Datename(dw, dbo.Download.Date_of_Download)+', '+CONVERT(VARCHAR(12), dbo.Download.Date_of_Download, 107) as Date_to_Display,
dbo.Download.Number_of_Computers
FROM dbo.Download
ORDER BY dbo.Download.Date_of_Download DESC
In SQL Server version 2012 and later, there is the FORMAT TSQL function that can do what you want. The "dddd" portion does day of the week:
SELECT
FORMAT(dbo.Download.Date_of_Download, 'dddd MMM dd, yyyy') as Date_to_Display,
dbo.Download.Number_of_Computers
FROM dbo.Download
ORDER BY dbo.Download.Date_of_Download DESC
MS docs: https://learn.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql

SQL query returns different results when run from Excel

A have a query that returns different results when run directly in SQL Server Management Studio and when run from Excel (using the SQLOLEDB provider). Both return a table with 12 rows (one per month) and two columns (date and a complex count), but some of the numeric values are incorrect in the Excel result set.
I'm happy to show you the full detail, but to start with can you suggest what type of things can cause such a difference?
Versions: SQL Server 10.50.4000, Excel 2013
Edit: the full details ...
select cast(ActualDate as date) as 'Start of rolling 12 months'
, count(distinct x.con_id) as 'Total Sponsors'
from DateTimeDimV4.dbo.datedim
join (select cm_id, con_id
, cm.start_date as activation_date
, isnull(stop_date, getdate()) as stop_date
from cm
join con_act ca on ca.con_act_db_id = cm.con_act_db_id and ca.con_act_id = cm.con_act_id
where
ca.code = 'corres'
) X on cast(activation_date as date) <= cast(ActualDate as date)
and cast(stop_date as date) > cast(ActualDate as date)
where
--ActualDate = eomonth(ActualDate) -- only works in SQL 2012, so instead we use ...
ActualDate = DATEADD(dd, -DAY(DATEADD(mm, 1, ActualDate)), DATEADD(mm, 1, ActualDate))
and ActualDate >= '31 Jul 2012' and ActualDate <= '30 June 2013'
group by cast(ActualDate as date)
order by cast(ActualDate as date)
In SSMS, this returns ...
Start of rolling 12 months Total Sponsors
2012-07-31 862
2012-08-31 872
2012-09-30 872
2012-10-31 880
2012-11-30 876
2012-12-31 878
2013-01-31 882
2013-02-28 888
2013-03-31 887
2013-04-30 887
2013-05-31 920
2013-06-30 933
But in Excel I get ...
Start of rolling 12 months Total Sponsors
2012-07-31 862
2012-08-31 872
2012-09-30 872
2012-10-31 880
2012-11-30 876
2012-12-31 878
2013-01-31 882
2013-02-28 887
2013-03-31 887
2013-04-30 887
2013-05-31 887
2013-06-30 887
Note that the first seven rows are identical but that Excel repeats the same incorrect value in the last five rows.
Also note that if I change the literal dates from '31 Jul 2012' and '30 June 2013' to '31 Jul 2011' and '30 June 2012' then the two environments produce results that are identical to each other.
Try changing:
and ActualDate >= '31 Jul 2012' and ActualDate <= '30 June 2013'
to:
and ActualDate >= '2012-07-31' and ActualDate <= '2013-06-30'
My logic: I think that MS Query is interpreting the literal date differently than SSMS. I can't prove it, though, since I can't find any documentation on MS Query. Scratch that. Let's just call it a hunch.
I usually stick with the ISO date formats for all my date literals.
Also, why did you abbreviate July but not June?
PICNIC indeed! Sorry for wasting your time.
The Excel version was executing the query against the correct server, but the wrong database. It was executing against a backup database whose name was only one character different from the live one.

Resources