how to separate date? - sql

In a database
Date
5/29/2013
12/4/2013
12/1/2014
The output will be like this
Year Month date
2013 5 29
2013 12 4
2014 12 1
I tried this code:
select [Date],
right([Date],4) as year ,
left([Date],CHARINDEX('/',[Date])-1) as month ,
substring([Date],3,2) as date
FROM Table1
but it not showed the result properly.

DECLARE #datevar varchar(50) = '10/10/2014'
declare #date datetime = convert(date,#datevar,101)
SELECT datepart(year, #date) AS 'year'
,DATEPART(month, #date) AS 'Month'
,DATEPART(day, #date) AS 'Day'
you can use this also.

Please try:
select
Year(CONVERT(Datetime, [Date])) [Year],
Month(CONVERT(Datetime, [Date])) [Month],
Day(CONVERT(Datetime, [Date])) [Date]
FROM Table1

Try this:
SELECT DATEPART(yyyy,date) AS Year,
DATEPART(mm,date) AS Month,
DATEPART(dd,date) AS Day,
FROM Table1
http://www.w3schools.com/sql/func_datepart.asp

create table #t(id varchar(10))
insert into #t values('5/29/2013'),
('12/4/2013'),
('12/1/2014')
select year(id) as [year],month(id) as [month],day(id) as [day] from #t

As Date is a varchar column, first convert it to DateTime and then do the manipulations as :
SET DATEFORMAT MDY;
select [Date],
cast ([Date] as Datetime),
Year(cast ([Date] as Datetime)) [Year],
Month(cast ([Date] as Datetime)) [Month],
Day(cast ([Date] as Datetime)) [Date]
FROM Table1
DEMO

Please try this too :
select datepart(year,[Date]) [year],
datepart(month,[Date]) [month],
datepart(day,[Date]) [day]
FROM table1

Why are you doing so Just do as written below
SELECT CONVERT(DATE,[date]) ,
YEAR = DATEPART(YEAR , CONVERT(DATETIME, [date])),
MONTH = DATEPART(MONTH , CONVERT(DATETIME, [date])),
DAY = DATEPART(DAY, CONVERT(DATETIME, [date]))
FROM DateTable
You can also use other formats if your data is not in this format

Related

how to get data dynamically in view basing on fiscal year

How can i create a view Dynamically to get the data based on fiscal year(Financial year).
Lets have look at sample data where im having sample data.
Declare #t table(StartDate date )
insert into #t values('04/01/2012'),
('01/01/2012'),
('09/15/2013'),
('04/01/2014'),
('01/01/2015'),
('09/15/2015'),
('04/01/2016'),
('01/01/2017'),
('09/15/2016')
Just take an example if I have ran the view today I need to get from March 2016 to April 2017. If I have ran view on May 2017 I need to get data from march 2017 to upto may 2017.
I can work it out in Sql server scripts or Stored procedure but how can I achieve the same result in Dynamic View or View .
Suggest me !
my script
DECLARE #STARTDATE DATETIME, #ENDDATE DATETIME,#CURR_DATE DATETIME
SET #CURR_DATE='2016-06-01'
IF MONTH(#CURR_DATE) IN (1,2,3)
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
END
ELSE
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
END
select * from #t
where StartDate between
#STARTDATE AND #ENDDATE
order by year (StartDate)
it's giving data what I want for the fiscal year (2016-2017)
but how can I use this and create a VIEW
select t.*,getdate()
from #t t
where year(startdate) * 100 + month(startdate) >=
case
when month(getdate()) in (1,2,3) then (year(getdate()) * 100) + 3 - 100
else (year(getdate()) * 100) + 3
end
You can use cte with dates based on current date (GETDATE()) in a view:
;WITH cte AS (
SELECT CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE())-1 AS VARCHAR)+'/04/01' AS DATE) ELSE CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/04/01' AS DATE) END AS StartDate,
CASE WHEN MONTH(GETDATE()) IN (1,2,3) THEN CAST( CAST(YEAR(GETDATE()) AS VARCHAR)+'/03/31' AS DATE) ELSE CAST( CAST(YEAR(GETDATE())+1 AS VARCHAR)+'/03/31' AS DATE) END AS EndDate
)
SELECT t.*
FROM YourTable t
INNER JOIN cte c
ON t.StartDate between c.StartDate AND c.EndDate
ORDER BY year(t.StartDate)
If you already worked out the code in a script\stored procedure you can re-use such code in a Table-Valued User-Defined Functions.
That way you will be able to query the UDF like a view.
You can try something like this:
select t.*
from #t t
cross join (
select startdate = case
when MONTH(#CURR_DATE) IN (1,2,3)
then CAST( CAST(YEAR(#CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
else CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
end) s
cross join (
select enddate = case
when MONTH(#CURR_DATE) IN (1,2,3)
then CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
else CAST( CAST(YEAR(#CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
end) e
where t.StartDate between s.startdate and e.enddate
order by year (t.StartDate)

Calendar showing null when date begins in previous year

This is the syntax I am using to create my calendar. The issue that I have is that since the startdate of Week1 is in 2012, startdate is showing as null. Is there a way to have the startdate (or enddate in other instances) populate even when it is in a different year? #Winds Of Change ---
That adds in a start date and end date where previously it was null. But what I am after is for example, I need my date range to run Sat - Wed. So let's take week 53 for 2013. The date range should be 12/28/2013 -- 01/01/14. Is there a way to tinker the calander into displaying in that format?
CREATE TABLE dbo.Calendar (
CalendarYear INT NOT NULL,
CalendarWeek INT NOT NULL,
WeekStartDate VARCHAR(50),
WeekEndDate VARCHAR(50),
CONSTRAINT PK_Calendar PRIMARY KEY (
CalendarYear,
CalendarWeek
)
)
SET DATEFIRST 6
DECLARE #StartDate DATETIME,
#NumOfDays INT
SET #StartDate = '20130101'
SET #NumOfDays = 1000;
WITH calendar
AS (
SELECT TOP (#NumOfDays) dateadd(day, row_number() OVER (
ORDER BY sc1.column_id
) - 1, #StartDate) AS CalendarDate
FROM sys.columns sc1
CROSS JOIN sys.columns sc2
)
INSERT INTO dbo.Calendar (
CalendarYear,
CalendarWeek,
WeekStartDate,
WeekEndDate
)
SELECT DATEPART(year, c.CalendarDate) AS Year,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week,
MAX(CASE DATEPART(WEEKDAY, c.CalendarDate)
WHEN 1
THEN convert(VARCHAR(50), c.CalendarDate, 101)
ELSE NULL
END) AS StartDate,
MAX(CASE DATEPART(WEEKDAY, c.CalendarDate)
WHEN 7
THEN convert(VARCHAR(50), c.CalendarDate, 101)
ELSE NULL
END) AS EndDate
FROM calendar c
GROUP BY DATEPART(year, c.CalendarDate),
DATEPART(Week, c.CalendarDate)
ORDER BY Year,
startdate,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) --Week
SELECT *
FROM dbo.Calendar
So your problem is is that you're grouping by week and year, but at the beginning/end of the year, the year begins/ends on a different week. So if the first week starts on Wednesday, it's only a 3 day week for that Year.
I've had a small tinker, and I've got it working so that it displays the first/last day of the year as the start/end date of the week, by changing things around. Here is my modified version:
SELECT
DATEPART(year, c.CalendarDate) AS Year,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) AS Week, --DATEPART(week, c.CalendarDate) AS Week,
convert(VARCHAR(50), MIN(c.CalendarDate), 101) AS StartDate,
convert(VARCHAR(50), MAX(c.CalendarDate), 101) AS EndDate
FROM
calendar c
GROUP BY
DATEPART(year, c.CalendarDate),
DATEPART(Week, c.CalendarDate)
ORDER BY
Year,
startdate,
convert(VARCHAR(100), DATEPART(week, c.CalendarDate)) --Week
Hope this helps.
EDIT: In response to your comment/edit, have a look at these update statements. Put them after your insert.
EDIT2: Don't use the above insert as well as the updates.
update dbo.Calendar set WeekStartDate = convert(VARCHAR(50), dateadd(day, 1, dateadd(week, -1, cast(WeekEndDate as datetime))), 101)
where WeekStartdate is null
update dbo.Calendar set WeekEndDate = convert(VARCHAR(50), dateadd(day, -1, dateadd(week, 1, WeekStartDate)), 101)
where WeekEndDate is null

Select empty weeks in SQL

I am grouping by weeks using DATEPART in SQL. However, I want to include the empty weeks also, not only weeks that include values. I have a script that works perfectly collecting data by weeks, but not the empty weeks. I´ve been trying to use left outer join but my SQL skills are not all that great. I decided to ask you guys.
Here is my script:
select
DatePart(Year, MYTABLE.CREATION_DATE) as DateYear,
DatePart(Month, MYTABLE.CREATION_DATE) as DateMonth,
DatePart(Week, MYTABLE.CREATION_DATE) as DateWeek,
sum(cast(MYTABLE.BASE_TRANSACTION_VALUE as int)) as Value,
min(MYTABLE.CREATION_DATE) as DateT
from MYTABLE
where MYTABLE.SEGMENT2 like '00601'
and MYTABLE.SEGMENT4 like '%'
and MYTABLE.CREATION_DATE > '2012-12-30 12:00:00'
and MYTABLE.CREATION_DATE < '2013-12-30 11:00:00'
group by
DatePart(Year, MYTABLE.CREATION_DATE),
DatePart(Month, MYTABLE.CREATION_DATE),
DatePart(Week, MYTABLE.CREATION_DATE)
order by DateYear, DateMonth, DateWeek
And this is the result of that script.
Could you guys possibly give me an example of a join clause could look like in this case?
[updated 2014-01-09 08:06 UTC]
you can create the dates dynamically (DateRange) and the outer-join them to your select like this:
declare #startdate date;
set #startdate = '2012-12-30';
declare #enddate date;
set #enddate = '2013-12-30'
;with DateRange AS
(
SELECT
DatePart(Year, #startdate) as DateYear,
DatePart(Month, #startdate) as DateMonth,
DatePart(iso_Week, #startdate) as DateWeek,
#startdate as DateValue
UNION ALL
SELECT
DatePart(Year, dateadd(dd,7,DateValue)) as DateYear,
DatePart(Month, dateadd(dd,7,DateValue)) as DateMonth,
DatePart(iso_Week, dateadd(dd,7,DateValue)) as DateWeek,
dateadd(dd,7,DateValue)
FROM DateRange
WHERE dateadd(dd,7,DateValue) <= #enddate
), data as (
select
DatePart(Year, MYTABLE.CREATION_DATE) as DateYear,
DatePart(Month, MYTABLE.CREATION_DATE) as DateMonth,
DatePart(iso_Week, MYTABLE.CREATION_DATE) as DateWeek,
sum(cast(MYTABLE.BASE_TRANSACTION_VALUE as int)) as Value,
min(MYTABLE.CREATION_DATE) as DateT
from MYTABLE
where MYTABLE.SEGMENT2 like '00601'
and MYTABLE.SEGMENT4 like '%'
and MYTABLE.CREATION_DATE > '2012-12-30 12:00:00'
and MYTABLE.CREATION_DATE < '2013-12-30 11:00:00'
group by
DatePart(Year, MYTABLE.CREATION_DATE),
DatePart(Month, MYTABLE.CREATION_DATE),
DatePart(iso_Week, MYTABLE.CREATION_DATE)
)
select
DateRange.DateYear,
DateRange.DateMonth,
DateRange.DateWeek,
data.Value,
data.DateT
from data
right outer join
DateRange
on
data.DateYear = DateRange.DateYear
and data.DateWeek = DateRange.DateWeek
order by
DateRange.DateYear,
DateRange.DateMonth,
DateRange.DateWeek
This should do it. My SQLFiddle is http://www.sqlfiddle.com/#!6/b777f/1/0
declare #WeekTable table(
[WeekDate] datetime
)
declare #startDate datetime,
#EndDate datetime
select #startDate = '1/1/2013',#EndDate = '12/31/2013'
while #startDate<=#EndDate begin
insert into #WeekTable values(#startDate)
set #startDate = #startDate+7
end
select
DatePart(Year, [WeekDate]) as DateYear,
DatePart(Month, [WeekDate]) as DateMonth,
DatePart(Week, [WeekDate]) as DateWeek,
sum(cast(MYTABLE.BASE_TRANSACTION_VALUE as int)) as Value,
min(isnull(MYTABLE.CREATION_DATE,[WeekDate])) as DateT
from
#WeekTable
left outer join
MYTABLE
on
DatePart(Week,MYTABLE.CREATION_DATE) =DatePart(Week, [WeekDate])
and
DatePart(Year,MYTABLE.CREATION_DATE) =DatePart(Year, [WeekDate])
and
MYTABLE.SEGMENT2 like '00601'
and
MYTABLE.SEGMENT4 like '%'
group by
DatePart(Year, [WeekDate]) ,
DatePart(Month, [WeekDate]),
DatePart(Week, [WeekDate])
order by
DateYear, DateMonth, DateWeek

calculate fiscal year in sql select statement?

I have a date field that needs to return in fiscal year format. example
Start_Date Year
04/01/2012 - 2013
01/01/2012 - 2012
09/15/2013 - 2014
We need to calculate
04/01/2012 to 03/31/2013 is FY 2013
and
04/01/2013 to 03/31/2014 is FY 2014
How can we do that in select statement?
David has a very good solution. A simpler expression is:
select year(dateadd(month, -3, start_date)) as FiscalYear
That is, subtract 3 months and take the year.
EDIT:
As noted in the comment, this seems to produce one year too early. Here are two solutions:
select year(dateadd(month, 9, start_date)) as FiscalYear
select 1 + year(dateadd(month, -3, start_date)) as FiscalYear
SELECT CASE WHEN DatePart(Month, Start_Date) >= 4
THEN DatePart(Year, Start_Date) + 1
ELSE DatePart(Year, Start_Date)
END AS Fiscal_Year
FROM data
I just chose to do it this way. It's easy and you can replace the 09,30 with whatever you want your fiscal year end to be. Not sure if this works in anything but SQL Server though.
CASE
WHEN CAST(GETDATE() AS DATE) >
SMALLDATETIMEFROMPARTS(DATEPART(YEAR,GETDATE()),09,30,00,000)
THEN
DATEPART(YEAR,GETDATE()) + 1 ELSE DATEPART(YEAR,GETDATE())
END AS FY
For Australian financial year, use the following:
SELECT
year(dateadd(MONTH, 6, DateColumn)) AS FY,
...
FROM ...
Assuming that you have a table Fiscal_Year with Start_Date per Year, and you want to find the fiscal year for a given date #Date:
SELECT MIN(Year) WHERE #Date >= Start_Date FROM Fiscal_Year
Declare #t table(StartDate date ,Year1 int)
insert into #t values('04/01/2012',2013),('01/01/2012',2012),('09/15/2013',2014)
;with CTE as
(select max(year1) maxyear from #t)
, cte1 as
(select cast('04/01/'+convert(varchar(4),a.year1) as date) FromFY,dateadd(day,-1,dateadd(year,1,cast('04/01/'+convert(varchar(4),a.year1) as date))) ToFY
,b.year1 from #t a inner join (select min(year1)year1 from #t) b on a.year1=b.year1
union all
select cast(dateadd(day,1,ToFY) as date),cast(dateadd(year,1,ToFY) as date),year1+1 year1 from cte1 where year1<=(select maxyear from cte)
)
select * from cte1
DECLARE #STARTDATE DATETIME, #ENDDATE DATETIME,#CURR_DATE DATETIME
SET #CURR_DATE='2015-01-30'
IF MONTH(#CURR_DATE) IN (1,2,3)
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE)-1 AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/03/31' AS DATE)
END
ELSE
BEGIN
SET #STARTDATE= CAST( CAST(YEAR(#CURR_DATE) AS VARCHAR)+'/04/01' AS DATE)
SET #ENDDATE= CAST( CAST(YEAR(#CURR_DATE)+1 AS VARCHAR)+'/03/31' AS DATE)
END
SELECT #STARTDATE AS ST_FI,#ENDDATE AS END_FY
...something simple :)
(YEAR(DATEADD(Month,-((DATEPART(Month,[Date])+5) %12),[Date]))+) AS Financial_Year
declare #Date smalldatetime, #FiscalYearStartMonth tinyint
set #Date = GETDATE();
set #FiscalYearStartMonth = 1; -- Jan
print convert(varchar(4),
case when MONTH(#Date) < #FiscalYearStartMonth
then YEAR(#Date) -1
else YEAR(#Date) end)
assuming #Date is your [Start_Date] field, you can:
select * from yourTable
group by convert(varchar(4),
case when MONTH([Start_Date]) < #FiscalYearStartMonth
then YEAR([Start_Date]) -1
else YEAR([Start_Date]) end)
Hope this helps
This is what would look like in oracle to get current financial year. Enter the date for which you want to find fiscal year in place of sysdate
SELECT '01-APR-'
||TO_CHAR((add_months(**sysdate**,-3)),'YYYY') FIN_YEAR_START_DATE,
'31-MAR-'
||(TO_CHAR((add_months(**sysdate**,-3)),'YYYY')+1) FIN_YEAR_END_DATE
FROM dual;
For only year format (FY 2020) use following query:
SELECT tender_opening_date,CASE WHEN MONTH( order_date) >= 4
THEN CONCAT('FY ',YEAR(( order_date)) +1 )
ELSE CONCAT('FY ',YEAR( order_date)-1 )
END AS Fiscal_Year
FROM orders_tbl
For full financial Year (FY 2019-20) use following query:
SELECT tender_opening_date,CASE WHEN MONTH( order_date) >= 4
THEN CONCAT('FY ',YEAR( order_date),'-',DATE_FORMAT( order_date,'%y') +1 )
ELSE CONCAT('FY ',YEAR( order_date)-1,'-',DATE_FORMAT( order_date,'%y') )
END AS Fiscal_Year
FROM orders_tbl

write a query that will run all the days and the name of the day between two set dates [duplicate]

This question already has answers here:
Get a list of dates between two dates
(23 answers)
Closed 8 years ago.
I am trying to write a query that will run all the days and the name of the day between two set dates.
Example:
Date1 = 12/28/2005
Date2 = 12/30/2006
Results:
12/28/2005 Wednesday
12/29/2005 Thursday
12/30/2005 Friday
12/31/2005 Saturday
01/01/2006 Sunday
01/02/2006 Monday
01/03/2006 Tuesday
Any help is appreciated!
You may check this fiddle.
The code:
DECLARE #Date1 DATETIME
DECLARE #Date2 DATETIME
SET #Date1 = '20051228'
SET #Date2 = '20061230'
;WITH cteSequence ( SeqNo) as
(
SELECT 0
UNION ALL
SELECT SeqNo + 1
FROM cteSequence
WHERE SeqNo < DATEDIFF(d,#Date1,#Date2)
)
SELECT CONVERT(VARCHAR,DATEADD(d,SeqNo,#Date1),1) + ' ' + DATENAME(dw,DATEADD(d,SeqNo,#Date1))
FROM cteSequence
OPTION ( MAXRECURSION 0);
GO
You can use that table-valued function:
create function DateTable
(
#FirstDate datetime,
#LastDate datetime,
#handle nvarchar(10)='day',
#handleQuantity int=1
)
returns #datetable table (
[date] datetime
)
AS
begin
with CTE_DatesTable
as
(
select #FirstDate AS [date]
union ALL
select case #handle
when 'month' then dateadd(month, #handleQuantity, [date])
when 'year' then dateadd(year, #handleQuantity, [date])
when 'hour' then dateadd(hour, #handleQuantity, [date])
when 'minute' then dateadd(minute, #handleQuantity, [date])
when 'second' then dateadd(second, #handleQuantity, [date])
else dateadd(day, #handleQuantity, [date])
end
from CTE_DatesTable
where #LastDate >=
case #handle
when 'month' then dateadd(month, #handleQuantity, [date])
when 'year' then dateadd(year, #handleQuantity, [date])
when 'hour' then dateadd(hour, #handleQuantity, [date])
when 'minute' then dateadd(minute, #handleQuantity, [date])
when 'second' then dateadd(second, #handleQuantity, [date])
else DATEADD(day, #handleQuantity, [date])
end
)
insert #datetable ([date])
select [date] from CTE_DatesTable
option (MAXRECURSION 0)
return
end
You can call it like:
select [date],datepart(weekday,[date]) from dbo.DateTable('12/28/2005','12/30/2006',default,default)
You didn't specify your DBMS so I'm assuming Postgres:
select i::date, to_char(i, 'Day')
from generate_series(timestamp '2005-12-28 00:00:00',
timestamp '2006-12-30 00:00:00', interval '1' day) i;
The ANSI SQL solution for this would be:
with recursive date_list (the_date) as (
values ( date '2005-12-28' )
union all
select cast(p.the_date + interval '1' day as date)
from date_list p
where p.the_date <= date '2006-12-30
)
select *
from date_list;