convert int to datetime in sybase - tsql

This works perfectly on the server (sql server 2012) for a julian date of 5 digits
select cast (column1 as DATETIME) FROM mytable
How to cast an int to datetime in sybase?
And which would be the best way, since I have a large table and I have to minimize the time i'm going to be using the server under the query.
I saw here: http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc32300.1570/html/sqlug/sqlug645.htm
that it is allowed to convert from int to varchar and from varchar to smalldate.
So maybe something like this, but i don't know the syntax for sybase:
declare #convDate varchar (200)
set #convDate = 'SELECT top 100 CONVERT( varchar (200), column1, 104 )as someCol FROM dbo.mytable'
select cast (#convDate as DateTime) as newDate into #myTemp from ?

Assuming date is in YYYYMMDD format. Use below:
SELECT CONVERT(DATETIME, CONVERT(VARCHAR, col1)) AS someCol FROM dbo.mytable

Internal numbers representing dates in Excel are a continuous sequence of integers from Jan 1 1900, which is number one. Hence, a solution is to use the function DATEADD to sum your integer (minus one) to Jan 1 1900. In this query, " " is the same as "Jan 1 1900" as this is the Sybase ASE default.
select dateadd(day, column1 - 1, " ") from mytable /* Probably wrong */
But I tested and got a one day difference. The result of this is Jul 13 2015, but Excel shows Jul 12 2015 instead.
select dateadd(day, 42197 - 1, " ")
IMHO, Excel is wrong, as it shows Feb 29 1900 for the number 60, but 1900 (contrary to 2000) is not a leap year. Sybase ASE is correct; this gives Feb 28 1900 and Mar 1 1900:
select dateadd(day, 59 - 1, " "), dateadd(day, 60 - 1, " ")
Assuming you had to take Excel convention, then just subtract two instead of one:
select dateadd(day, column1 - 2, " ") from mytable /* Bizarre but maybe OK */

Related

How to see value of a char column sorted as I need

The table name is Date , and one of it's column's name is MonthOfYear (for jan the column value is 1 , for feb it is 2 , for march : 3 ... )and the other column is MonthName : this column contains the name of month ( jan , feb , march ..)
I need to see the result sorted ( jan be the first col , then feb , then march , then ...)
I updated the MonthName like this but it didn't work :
update Date
set [monthname] = cast(monthofyear as nvarchar(3)) + ' ' + rtrim(ltrim([monthname]))
You cannot get what you want sort on a char column
As a char 12 will sort before 2
You need to search on an integer column for 12 to sort before 2
So sort on MonthOfYear
Order By MonthOfYear
I don't know all your column names, but you don't want to change the data in the MonthName column.
Have you tried:
SELECT Year, MonthName
FROM Date
ORDER BY Year, MonthOfYear
To order by a varchar column you can put a 0 at the front of the single digit numbers.
Here's an example that shows how you can do it:
declare #t table (StringNumber varchar(3))
insert into #t (StringNumber)
select '9' union
select '10' union
select '11'
select StringNumber
from #t
order by StringNumber
select StringNumber, right('0' + StringNumber, 2) as OrderByStringNumber
from #t
order by right('0' + StringNumber, 2)

Getting Dates by Selecting a week in oracle

I have a textbox with random numbers from 1 to 52 which are week numbers of a calendar and a drop down which mentions as years.
For example if I select 2 in a textbox with year 2014, then I want the dates to be mentioned as 05-1-2014 - 11-1-2014. Is it possible to do it.
Also I have tried one query which doesnt match my requirement
SELECT date_val, TO_CHAR (date_val, 'ww')
FROM (SELECT TO_DATE ('01-jan-2013', 'DD-MON-YYYY') + LEVEL AS date_val
FROM DUAL
CONNECT BY LEVEL <= 365)
Please help.
Try this. Here 2 is the number of week in the year (FirstSunday+(NumberOfWeek-1)*7 as WeekStart, FirstSunday+ NumberOfWeek*7-1 as WeekEnd) and 2014 is a year:
select
FirstSunday+(2-1)*7 as WeekStart,
FirstSunday+ 2*7-1 as WeekEnd
from
(
Select NEXT_DAY(TO_DATE('01/01/'||'2014','DD/MM/YYYY')-7, 'SUN') as FirstSunday
from dual
)
SQLFiddle demo
Try this too,
SELECT start_date,
start_date + 6 end_day
FROM(
SELECT TRUNC(Trunc(to_date('2014', 'YYYY'),'YYYY')+ 1 * 7,'IW')-1 start_date
FROM duaL
);

to_char() issue in PostgreSQL

I have a PostgreSQL table with a field named effective_date and data type is integer(epoch date). What I want to do is to select only the entries that have an effective_date of my choice (I only want to query by the month). My query is below and the problem is, it is not returning anything although the table do have many entries that match the selection criteria.
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND to_char(effective_date, 'Mon') = 'Jul'
AND deleted = 0";
Use extract(month from the_date) instead of to_char. See datetime functions in the Pg docs.
With to_char you'll suffer from all sorts of issues with case, localisation, and more.
Assuming you meant that the data type of effective_date was timestamp or date, you'd write:
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND extract(month from effective_date) = 7
AND deleted = 0";
If it's integer then - assuming it's an epoch date - you have to convert it to a timestamp with to_timestamp, then use extract on it. See the epoch section in the documentation linked to above, eg:
$query = "select *
from ". $this->getTable() ."
where pay_stub_entry_name_id = 43
AND extract(month from to_timestamp(effective_date)) = 7
AND deleted = 0";
The immediate cause of your problem was that you were calling to_char(integer,text) with an integer epoch date. Only the timestamp versions of to_char do date formatting; Mon isn't special for the others, so it was simply output as a literal string Mon. Compare:
regress=# SELECT to_char(current_timestamp, 'Mon');
to_char
---------
Aug
(1 row)
regress=# select to_char( extract(epoch from current_timestamp), 'Mon');
to_char
---------
Mon
(1 row)
Remember to parameterise your real-world versions of these queries to help avoid SQL injection.

Returning multiple months of data into one select

I have a question on SQL 2008 which is probably quite easy but I can't see the woods for the trees now.
I am trying to produce a sql based report detailing the last six months of helpdesk issue stats, per application, per office, per month which I then take into ssrs to apply prettiness :o)
Anyway - I have my script, which is fine on a month by month basis, for example;
SELECT distinct t.name_1 'Application',
(select distinct name from location where location_ref = c.location_ref) as office,
Count (t.name_1) as [Call Count],
datename(month, dateadd(month,-2,getdate()))+' '+datename(year, dateadd(month,-2,getdate())) as [Report Month]
FROM call_logging C
Inner Join problem_type t On t.ref_composite = c.ref_composite
AND c.resolve_time between onvert(datetime,convert(varchar,month(dateadd(m,-2,getdate()))) + '/01/' + convert(varchar,year(dateadd(m,-2,getdate()))))
and convert(datetime,convert(varchar,month(dateadd(m,-1,getdate()))) + '/01/' + convert(varchar,year(getdate())))
and c.resolve_group in ('48', '60')
which brings back all of May's issues.
The problem is that t.name_1 (the application in which the issue is for) is dynamic and the list grows or shrinks every month.
I basically need a layout of
APPLICATION OFFICE COUNT JUNE MAY APRIL MARCH FEB JAN
WORD LONDON 20 1 1 2 5 10 1
WORD PARIS 10 2 3 1 2 0 3
EXCEL MADRID 05 0 0 3 2 0 0
etc (if that makes sense on this layout!)
I've gone down the 6 separate reports road but it just doesn't look very nice in ssrs. I've thought about #tmptables but they don't like inserting distinct rows.
SELECT [C].[name_1] AS [APPLICATION]
,COUNT([name_1]) AS [CALL COUNT]
,[l].[location_ref]
,[dbo].[ufn_GetDateTime_CalenderYearMonth]([resolve_time]) AS [StartCalenderYearMonth]
FROM [call_logging] [C] INNER JOIN [problem_type] [t]
ON [t].[ref_composite] = [c].[ref_composite]
AND [c].[resolve_group] IN ('48', '60')
INNER JOIN [location] [l] ON [c].[location_ref] = [l].[location_ref]
WHERE [C].[resolve_time] BETWEEN '2011-01-01' AND GETDATE()
GROUP BY [C].[name_1], [l].[location_ref], [dbo].[ufn_GetDateTime_CalenderYearMonth]([resolve_time])
And the code for ufn_GetDateTime_CalenderYearMonth is:
CREATE FUNCTION [dbo].[ufn_GetDateTime_CalenderYearMonth] (#DateTime datetime)
RETURNS varchar(20)
AS
BEGIN
declare #dateString varchar(20)
declare #yearString varchar(10)
declare #monthString varchar(10)
set #yearString = cast( DATEPART(year, #DateTime) as varchar(10))
if(DATEPART(month, #DateTime) < 10)
set #monthString = '0' + cast( DATEPART(month, #DateTime) as varchar(5) )
else
set #monthString = cast( DATEPART(month, #DateTime) as varchar(5) )
set #dateString = #yearString + '-' + #monthString
RETURN (#dateString)
END
You just slap the resultset in a matrix and group everything by [StartCalenderYearMonth] and it will show numbers for each month from 1st of Jan 2011 till now..

Is it possible to set start of week for T-SQL DATEDIFF function?

I use DATEDIFF function to filter records added this week only:
DATEDIFF(week, DateCreated, GETDATE()) = 0
and I noticed what it's assumed what week starts on Sunday. But in my case I would prefer to set start of week on Monday. Is it possible somehow in T-SQL?
Thanks!
Update:
Below is an example showing what DATEDIFF doesn't check ##DATEFIRST variable so I need another solution.
SET DATEFIRST 1;
SELECT
DateCreated,
DATEDIFF(week, DateCreated, CAST('20090725' AS DATETIME)) AS D25,
DATEDIFF(week, DateCreated, CAST('20090726' AS DATETIME)) AS D26
FROM
(
SELECT CAST('20090724' AS DATETIME) AS DateCreated
UNION
SELECT CAST('20090725' AS DATETIME) AS DateCreated
) AS T
Output:
DateCreated D25 D26
----------------------- ----------- -----------
2009-07-24 00:00:00.000 0 1
2009-07-25 00:00:00.000 0 1
(2 row(s) affected)
26 Jul 2009 is Sunday, and I want DATEDIFF returns 0 in third column too.
Yes it possible
SET DATEFIRST 1; -- Monday
from http://msdn.microsoft.com/en-us/library/ms181598.aspx
It appears datediff doesn't respect the Datefirst, so make it do so run it like this
create table #testDates (id int identity(1,1), dateAdded datetime)
insert into #testDates values ('2009-07-09 15:41:39.510') -- thu
insert into #testDates values ('2009-07-06 15:41:39.510') -- mon
insert into #testDates values ('2009-07-05 15:41:39.510') -- sun
insert into #testDates values ('2009-07-04 15:41:39.510') -- sat
SET DATEFIRST 7 -- Sunday (Default
select * from #testdates where datediff(ww, DATEADD(dd,-##datefirst,dateadded), DATEADD(dd,-##datefirst,getdate())) = 0
SET DATEFIRST 1 -- Monday
select * from #testdates where datediff(ww, DATEADD(dd,-##datefirst,dateadded), DATEADD(dd,-##datefirst,getdate())) = 0
Stolen from
http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/8cc3493a-7ae5-4759-ab2a-e7683165320b
I have another solution.
This should be easier to understand, correct me if I am wrong
SET DATEFIRST 1
select DATEDIFF(week, 0, DATEADD(day, -##DATEFIRST, '2018-04-15 00:00:00.000'))
We subtract '-1' from date and Sunday will become Saturday (which is 7nth day of week)
and Mondфy(2) will first day of week
So if i'm getting this correctly,
the only thing we need to do is remove 1 day from both dates on our datediff as following :
DATEDIFF(week,dateadd(day,-1,cast(GETDATE() as date)),
dateadd(day,-1,cast([Date] as date))) as RollingWeek