How To Find First Date of All MOnths In A Year - sql

Hello every One i am trying to get Ist date of All months in A year
Like if Curretn year is 2012 and i want to get folowing results from a query
like
1-JAN-2012
1-FEB-2012
1-APR-2012
.
.
.
.
.
.
1-DEC-2012
Is there any one who can solve my problem thanks in advance

Just for completeness - here's a simpler version:
select ADD_MONTHS(TRUNC(SYSDATE,'Y'),ROWNUM-1)
from dual connect by level <= 12;

A calendar table is easier to use. Where I work, for example, you'd just run this query.
select cal_date
from calendar
where year_of_date = 2012
and day_of_month = 1;
There's a lot to be said for a query being obvious.

Please try the following. You may want to tweak the date format/timezone
select to_date('2012/'||l||'/01', 'yyyy/mm/dd')
from (select level l from dual connect by level < 13)
EDIT: As provided by the op in the comments, the current year needs to be taken rather than hardcoding it. The updated query is
SELECT L || '/01/' || TO_CHAR (SYSDATE, 'YYYY') DATESS FROM
(SELECT LEVEL L FROM DUAL CONNECT BY LEVEL < 13)

If you want to use solely date functions to get the value for a specific year you can use the following, also SQL Fiddle'd:
select add_months(trunc(last_day(add_months(trunc(to_date('2011'
,'yyyy')
, 'y')
, -1)
) + 1
)
, level - 1)
from dual
connect by level <= 12
This turns your "year" into a date, truncates that to the 1st of January as by default to_date('2011', 'yyyy') returns the current date in that year. It then removes a month, taking us to the 1st December 2010. Get's the last day of that month, the 31st December and adds a day, so back to the 1st of January, but I also do a connect by level and add the level - 1, i.e. 0 in January to return the correct day.
Unfortunately, Oracle doesn't have a first_day function, which would make this a lot easier.
It's roughly the same for the current year:
select add_months(trunc(last_day(add_months(trunc(sysdate,'y'),-1)) + 1), level - 1)
from dual
connect by level <= 12

Related

How to get entries from a SQL table for past 22 weekdays/ 8 Weekends

I want to get entries from the table for the past 22 weekdays or 8 weekends
I have one created_on column which serves as source of information for finding when the entry was created
I use it to extract dow and filter output by weekday and weekend
But I'm not able to figure out how can I get data for exactly 22 weekdays?
An example query would really help
You can use BETWEEN.
Example,
WHERE tablename.created_on BETWEEN "01.06.2022" AND "15.06.2022"
You could use the 'DY' date mask to filter the days and CONNECT BY LEVEL to get the date counts
SELECT t.something, t.created_on
FROM your_table t
WHERE 22 = (SELECT COUNT(1)
FROM DUAL
WHERE TO_CHAR(TRUNC(t.created_on ,'DD') + LEVEL - 1, 'DY') NOT IN ('SAT', 'SUN')
CONNECT BY LEVEL <= SYSDATE - TRUNC(t.created_on,'DD') + 1);

Calculate current quarter Fiscal_start date based off 13 week (91 day) rolling quarters

I am looking for a SQL solution to work in Oracle Developer SQL that will calculate the current quarters start and end date based off of sysdate and that the Fiscal calendar starts on Feb 1, 2020. Each quarter is a Fixed 13 weeks (91 days) -- NOT 3 months, therefore each year has a slightly different fiscal calendar.
Code will be uploaded to automated reporting and do not want to adjust it each year.
Current year fiscal calendar attached as sample explanation.
Current Fiscal Calendar
I started to head down this road but got lost when i realized the start date wasnt able to be correct in this format.
End solution would be used for a where clause to determine reporting date range such as
( Where Report_Date between Modified_Quarter_Start and sysdate )
select trunc(add_months(add_months(trunc(sysdate,'Y') -1 ,
to_number(to_char(sysdate,'Q')) * 3),-1),'MM')
start_date,trunc(add_months(add_months(trunc(sysdate,'Y') -1 ,
to_number(to_char(sysdate,'Q')) * 3),+2),'MM')-1 Endd_date,
add_months(trunc(sysdate,'Y') -1 ,to_number(to_char(sysdate,'Q')) * 3) end_date ,
to_char(sysdate,'YYYY - q') qtr from dual
Greatly appreciate any assistance.
Posting incase someone else runs into the same predicement in the future.
After reading a mention of a case statement for fixed days in another thread, i thought of this solution.
Select Trunc(sysdate - to_date('02-Feb-2019')),
Case When Trunc(sysdate - to_date('02-Feb-2019')) > 91 Then to_date('02-Feb-2019') +
Round( to_number(Trunc(sysdate - to_date('02-Feb-2019'))/91),0) * 91
Else null End Current_Quarter_Start,
Case When Trunc(sysdate - to_date('02-Feb-2019')) > 91 Then to_date('02-Feb-2019') +
( (Round( to_number(Trunc(sysdate - to_date('02-Feb-2019'))/91),0) +1 )* 91)-1 Else null End Current_Quarter_End From Dual

SQL computing and reusing fiscal year calculation in sql query

I have a condition in my SQL query, using Oracle 11g database, that depends on a plan starting or ending with in a fiscal year:
(BUSPLAN.START_DATE BETWEEN (:YEAR || '-04-01') AND (:YEAR+1 || '-03-31')) OR
(BUSPLAN.END_DATE BETWEEN (:YEAR || '-04-01') AND (:YEAR+1 || '-03-31'))
For now, I am passing in YEAR as a parameter. It can be computed as (pseudocode):
IF CURRENT MONTH IN (JAN, FEB, MAR):
USE CURRENT YEAR // e.g. 2015
ELSE:
USE CURRENT YEAR + 1 // e.g. 2016
Is there a way I could computer the :YEAR parameter within in an SQL query and reuse it for the :YEAR parameter?
CTEs are easy, you can make little tables on the fly. With a 1 row table you just cross join it and then you have that value available every row:
WITH getyear as
(
SELECT
CASE WHEN to_char(sysdate,'mm') in ('01','02','03') THEN
EXTRACT(YEAR FROM sysdate)
ELSE
EXTRACT(YEAR FROM sysdate) + 1
END as ynum from dual
), mydates as
(
SELECT getyear.ynum || '-04-01' as startdate,
getyear.ynum+1 || '-03-31' as enddate
from getyear
)
select
-- your code here
from BUSPLAN, mydates -- this is a cross join
where
(BUSPLAN.START_DATE BETWEEN mydates.startdate AND mydates.enddate) OR
(BUSPLAN.END_DATE BETWEEN mydates.startdate AND mydates.enddate)
note, values statement is probably better if Oracle has values then the first CTE would look like this:
VALUES(CASE WHEN to_char(sysdate,'mm') in ('01','02','03') THEN
EXTRACT(YEAR FROM sysdate)
ELSE
EXTRACT(YEAR FROM sysdate) + 1)
I don't have access to Oracle so I might have bugs typos etc since I didn't test.
In the code you shared there is a problem and a potential problem.
Problem, implicit conversion to date without format string.
In (BUSPLAN.START_DATE BETWEEN (:YEAR || '-04-01') AND (:YEAR+1 || '-03-31')) two strings are being formed and then converted to dates. The conversion to date is going to change depending on the value of NLS_DATE_FORMAT. To insure that the string is converted correctly to_date(:YEAR || '-04-01', 'YYYY-MM-DD').
Potential problem, boundary at the end of the year when time <> midnight.
Oracle's date type holds both date and time. A test like someDate between startDate and endDate will miss all records that happened after midnight on endDate. One simple fix that precludes use of indexes on someDate is trunc(someDate) between startDate and endDate.
A more general approach is to define date ranges and closed open intervals. lowerBound <= aDate < upperBound where lowerBound is the same asstartDateabove andupperBoundisendDate` plus one day.
Note: Some applications used Oracle date columns as dates and always store midnight, if your application is of that sort, then this is not a problem. And check constraints like check (trunc(dateColumn) = dateColumn) would make sure it stays that way.
And now, to answer the question actually asked.
Using subquery factoring (Oracle's terminology) / common table expression (SQL Server's terminology) one can avoid repetition within a query.
Instead of figuring out the proper year, and then using strings to put together dates, the code below starts by getting January 1 at Midnight of the current calendar year, trunc(sysdate, 'YEAR')). Then it adds an offset in months. When the months are Jan, Feb, Mar, the current fiscal year started last year on 4/1, or nine months before the start of this year. The offset is -9. Else the current fiscal year started 4/1 of this calendar year, start of this year plus three months.
Instead of end date, an upper bound is calculated, similar to lower bound, but with the offsets being 12 greater than lower bound to get 4/1 the following year.
with current_fiscal_year as (select add_months(trunc(sysdate, 'YEAR')
, case when extract(month from sysdate) <= 3 then -9 else 3 end) as LowerBound
, add_months(trunc(sysdate, 'YEAR')
, case when extract(month from sysdate) <= 3 then 3 else 15 end) as UpperBound
from dual)
select *
from busplan
cross join current_fiscal_year CFY
where (CFY.LowerBound <= busplan.start_date and busplan.start_date < CFY.UpperBound)
or (CFY.LowerBound <= busplan.end_date and busplan.end_date < CFY.UpperBound)
And yet more unsolicited advise.
The times I've had to deal with fiscal year stuff, avoiding repetition within a query was low hanging fruit. Having the fiscal year calculations consistent and correct among many queries, that was the essence of the work. So I'd recommend a developing PL/SQL package that centralizes fiscal calculations. It might include a function like:
create or replace function GetFiscalYearStart(v_Date in date default sysdate)
return date
as begin
return add_months(trunc(v_Date, 'YEAR')
, case when extract(month from v_Date) <= 3 then -9 else 3 end);
end GetFiscalYearStart;
Then the query above becomes:
select *
from busplan
where (GetFiscalYearStart() <= busplan.start_date
and busplan.start_date < add_months(GetFiscalYearStart(), 12))
or (GetFiscalYearStart() <= busplan.end_date
and busplan.end_date < add_months(GetFiscalYearStart(), 12))

Number of particular days between two dates

Is there an "easy" way to calculate the count of a particular day between two dates (e.g., say I wanted to know the number of Tuesdays between 1st January, 2000 and today)? Moreover, the same question applies more broadly to different units (e.g., how many 2pms between two dates, how many Februaries, how many 21st Augusts, etc.)... The best I've come up with (for days between dates) is this:
with calendar as (
select to_char(:start + level - 1, 'DAY') dayOfWeek
from dual
connect by level <= ceil(:end - :start)
)
select dayOfWeek, count(dayOfWeek)
from calendar
group by dayOfWeek;
I would have to create a view of this -- hardcoding the start and end dates -- to make it convenient(ish) to use; either that or write a function to do the dirty work. That wouldn't be difficult, but I'm wondering if there's already an Oracle function that could do this, accounting for things like leap days, etc.
EDIT This popped up in the related links when I posted this. That more-or-less answers the question for days and I know there's a months_between function that I could use for particular months. Any other related functions I should know about?
Replace start/end dates with your dates. This query calc number of TUE from Jan 1-2013 till today, which is 18:
SELECT count(*) number_of_tue
FROM
(
SELECT TRUNC(TO_DATE(Sysdate), 'YEAR') + LEVEL-1 start_dt
, To_Char(TRUNC(TO_DATE(Sysdate), 'YEAR') + LEVEL - 1, 'DY') wk_day
, To_Char(TRUNC(TO_DATE(Sysdate), 'YEAR') + LEVEL - 1, 'D') wk_day#
, trunc(Sysdate) end_dt
FROM DUAL
CONNECT BY LEVEL <= trunc(Sysdate) - trunc(Sysdate, 'YEAR') -- replace with your start/end dates
)
WHERE wk_day# = 3 -- OR wk_day = 'TUE' --
/

How can I get a table of dates from the first day of the month, two months ago, to yesterday?

I have a situation that I would normally solve by creating a feeder table (for example, every date between five years ago and a hundred years into the future) for querying but, unfortunately, this particular job disallows creation of such a table.
So I'm opening this up to the SO community. Today is Jan 29, 2010. What query could I run that would give a table with a single date column with values ranging from Nov 1, 2009 through Jan 28, 2010 inclusive? On Feb 1, it should give me every date from Dec 1, 2009 through Jan 31, 2010.
I'm using DB2 but I'm happy to see any other solutions on the off-chance they may provide a clue.
I know I can select CURRENT DATE from sysibm.sysdummy1 (or dual for Oracle bods) but I'm not sure how to immediately select a date range without a physical backing table.
This just does sequential days between two dates, but I've posted to show you can eliminate the recursive error by supplying a limit.
with temp (level, seqdate) as
(select 1, date('2008-01-01')
from sysibm.sysdummy1
union all
select level, seqdate + level days
from temp
where level < 1000
and seqdate + 1 days < Date('2008-02-01')
)
select seqdate as CalendarDay
from temp
order by seqdate
Update from pax:
This answer actually put me on the right track. You can get rid of the warning by introducing a variable that's limited by a constant. The query above didn't have it quite right (and got the dates wrong, which I'll forgive) but, since it pointed me to the problem solution, it wins the prize.
The code below was the final working version (sans warning):
WITH DATERANGE(LEVEL,DT) AS (
SELECT 1, CURRENT DATE + (1 - DAY(CURRENT DATE)) DAYS - 2 MONTHS
FROM SYSIBM.SYSDUMMY1
UNION ALL SELECT LEVEL + 1, DT + 1 DAY
FROM DATERANGE
WHERE LEVEL < 1000 AND DT < CURRENT DATE - 1 DAY
) SELECT DT FROM DATERANGE;
which outputs, when run on the 2nd of February:
----------
DT
----------
2009-12-01
2009-12-02
2009-12-03
: : : :
2010-01-30
2010-01-31
2010-02-01
DSNE610I NUMBER OF ROWS DISPLAYED IS 63
DSNE616I STATEMENT EXECUTION WAS SUCCESSFUL.
just an idea (not even sure how you'd do this), but let's say you knew how many days you wanted. Like 45 days. If you could get a select to list 1-45 you could do date arithmetic to subtract that number from your reference data (ie today).
This kind of works (in MySQL):
set #i = 0;
SELECT #i:=#i+1 as myrow, ADDDATE(CURDATE(), -#i)
FROM some_table
LIMIT 10;
The trick i have is how to get the 10 to be dynamic. If you can do that then you can use a query like this to get the right number to limit.
SELECT DATEDIFF(DATE_SUB(CURDATE(), INTERVAL 1 DAY),
DATE_SUB(LAST_DAY(CURDATE()), INTERVAL 2 MONTH))
FROM dual;
I haven't used DB2 before but in SQL Server you could do something like the following. Note that you need a table with at least the number of rows as you need days.
SELECT TOP 45
DATEADD(d, ROW_NUMBER() OVER(ORDER BY [Field]) * -1, GETDATE())
FROM
[Table]