Please suggest a method where in we could retrieve name of all months in between two dates.
The months may or may not contain data, but as the need is to display monthly trend, we are required to fetch all months in between two date ranges with or without data.
The Output will be like:
Jan | Feb | Mar
----------------------
Data | Data| Data
If you use SQL Server, you can use the MONTH() or DATEPART() function to extract the month from a date. For example, the following statement returns the current month in SQL Server: SELECT MONTH(CURRENT_TIMESTAMP); SELECT DATEPART(month, CURRENT_TIMESTAMP);
You could then do a GROUP BY to determine how many events occur per month
In general "dynamic columns" are much harder to achieve than "dynamic rows" so output that looks like the first of the tables below will be easier to achieve than output that looks like the second.
Easier
Month | Data
-------------
Jan | Data
Feb | Data
Mar | Data
Harder
Jan | Feb | Mar
----------------------
Data | Data | Data
In general, the best approach is to have your SQL queries return data in the first type of structure and then if required transform this to the second type in your "presentation layer", which might be in Excel, PowerBI, SSRS, or on a website, for example.
If you have months where there might be no data to be returned, you need some means of generating the months and then outer joining this to the data. Obviously in general, at least behind the scenes you'll want to be including years in your data in addition months as otherwise all the data from Jan 2020 will be grouped together with that from Jan 2021, which is probably not what you want.
Here is a SQL-Server-friendly snippet which will output all the months (and years) between two dates. At the time of writing, you haven't specified a DBMS, so if you aren't on SQL Server, this may not work for you.
DECLARE #datefrom DATE = '2020-06-01'
DECLARE #dateto DATE = '2021-03-01';
WITH cte AS
(
SELECT #datefrom as MyDate
UNION ALL
SELECT DATEADD(month,1,MyDate)
FROM cte
WHERE DATEADD(month,1,MyDate)<=#dateto
)
SELECT
YEAR(cte.MyDate) CalendarYear,
MONTH(cte.MyDate) CalendarMonth,
DATENAME(month, cte.MyDate) as MonthNameFull,
CONVERT(char(3),cte.MyDate,0) as MonthName3Char
FROM
cte
ORDER BY
Year(cte.MyDate),
Month(cte.MyDate)
The final SELECT query could be OUTER JOINed to your actual data to give you your desired results. Pivoting should then be done in the presentation layer.
An alternative to the cte would be to use a "numbers table" and use that to add a number of months to the start date and limit the output to where the result of adding that number of months is between the two provided dates.
Related
I have a database table which is named as table and there is a column Col which is present in table with datatype varchar. Column Col contains dates in the format MMM-YY.
For example Col has values as :
Col
DEC-21
NOV-21
SEP-20
OCT-19
DEC-21
As, we can see data can be duplicated like DEC-21. I want to extract last 6 months data based on the recent month present in Col. For example, If the DEC-21 is the most recent date(consider, day is not present) and so, I want data from DEC-21 to JUN-21 i.e. 12-21 to 06-21 if we map DEC to 12 and JUN to 06. This Table has many columns and one of the columns is Col which I mentioned above and I have to extract data based on the column Col by using SQL query.
I have written a query as:
SELECT *
FROM table
WHERE CAST(RIGHT(Col,4) AS INT) Between 2020 and 2021
But here I get data between 2020 and 2021. So, By doing some modification in the above query or Is there any other way to get the past 6 months data from the recent date which is in MMM-YYYY format from Col column.
I was writing code in R and I was using dbGetQuery() where I have to pass the SQL query. I have already done this thing after storing it in a dataframe but is there any way to do it directly by sql query ?
Any help would be appreciated.
with data as (
select *,
convert(date, '01-' + dt, 105) as converted_dt,
max(convert(date, '01-' + dt, 105)) over () as last_converted_dt
from T
)
select * from data
where converted_dt >= dateadd(month, -6, last_converted_dt);
The 105 comes from the list of date formats which can be found in the documentation for cast/convert. SQL Server can convert strings like Apr 2021 so a cast like below might also work (if you actually have four-digit years) but it's best to be explicit about the format as I did above.
cast(replace(dt, '-', ' ' as date)
Something like this should work.
SELECT * FROM table where CONVERT(DATE,'01-'+Col) BETWEEN '01-Jun-2021' and '31-Dec-2021'
I am using datepart function in SP. It is used to compare week and year of specified date.
Now my query arise as new year starts. I have one table called 'Task' and it is storing tasks date wise. Now When I execute SP with DATEPART(YY,'2016-01-05') . It is giving proper 2016's data. But I execute it with DATEPART(ISOWK,'2016-01-05') , it is giving 2015's data also with 2016's data.
I want data from 28th dec,2015 to 2nd jan,2016. Data of the week. And I am not able get data of 1st and 2nd Jan in that. Please help me with this.
Thanks,
ISOWK return the week number
You are trying to get date from 2015-12-28 to 2016-01-02.
The week number of 2015-12-28 is 53 and 2016-01-02 is 53
If you already have your start and end dates decided then you could use a simple query as shown below to filter on date range.
When mentioning date string in your query make sure you stick to this format :yyyymmdd which SQL Server will automatically understand. You don't need DATEPART to get records between two dates.
Query for filtering on a date range
SELECT TaskID, TaskDescription
FROM Tasks
where TaskDate between '20151228' and '20160102'
Another query you can use for date range filtering
SELECT TaskID, TaskDescription
FROM Tasks
where TaskDate >= '20151228' and TaskDate <= '20160102'
I have a column with 3 columns. I have multiple records for a year. As you see some of my records as follows
ID stardate enddate
1 1/1/2010 5/3/2010
2 2/4/2010 NULL -**EDIT**
3 1/2/2011 5/6/2011
4 3/4/2011 NULL -**EDIT**
I want to get a result for the earliest date in that year and the last date in that year. So output could be like
**EDITED:** 1/1/2010 12/31/2010 - For Year 2010
**EDITED:** 1/2/2011 12/31/2011 - For Year 2011
How can i get that in a query?If you need more info,please ask. Thanks
EDIT: If for the year if one of the columns read NULL then I have to consider the last day of the year as the enddate. i.e.12/31/YYYY. And I need to do that for each year again.
Assuming you use DATE (or related) columns in a MySQL table, something like this should serve your request:
SELECT MIN(startdate),
MAX(enddate),
YEAR(startdate)
FROM my_table
GROUP BY YEAR(startdate);
This groups all entries by year (of the startdate) and show you the minimum and maximum entries for each year as you want. See also the documentation for the DATE function in MySQL.
There are similar date functions and possibilities if you are using an other database system. Usually you can easily find them by googling the database system and something like "date functions".
select MIN(stardate),max(enddate)
from [Tablename]
where YEAR(enddate)=2013
I have a doubt in writing sql.
I had a farmerfields table with
YEAR,SEASON,Number of Fields.
and season look like this
Kharif---- 15june-15Oct
Rabi---15 oct to 15 Feb
Summer----15Feb to 15 June
now i want to write sql which returns all the rows excluding the current season in the current year. ie we should get the current season based on system date.
I am cracking my brain to get this, but could not.
Please help me.
I would suggest that you define a seasons table with three rows as above, e.g.
create table season (
season_id int,
description varchar(32),
start_day_of_month int,
start_month int
end_day_of_month int,
end_month int
)
the year is not included here just the day of month and month indices.
Your farmerfields table should then have a seaon_id column referring to this and most likely have a year column too.
Depending on your SQL vendor different date functions will be available but should should be able to compose a start and end date using the year from farmerfields and the month and day-of-month from season. Given this you can then determine if the current date falls within a given farmerfield entry's start and end dates.
Your table structure is wrong and not fit for what you need.
Instead of single field called SEASON, have two fields: SEASON_START and SEASON_END both of type Date then the query is as simple as:
Select * From [farmerfields] Where GetDate() Between SEASON_START And SEASON_END
If the names are part of your current SEASON field, add third field SEASON_NAME as well and the new structure will be:
SEASON_NAME | SEASON_START | SEASON_END
---------------------------------------
Kharif | 15june | 15Oct
Rabi | 15 oct | 15 Feb
...
Edit: in my above sample code I assumed you have SQL Server database - in case of different database you'll have different function to get current system date.
For difference of dates you can use the sql function DATEDIFF
SELECT * FROM table WHERE `date` BETWEEN '2011-10-20' AND '2011-1-1' AND DATEDIFF(`date`, '2011-10-20') % 10 = 0
I would suggest that you define a seasons table with three rows as above, e.g.
create table season (
season_id int,
description varchar(32),
start_day_of_month int,
start_month int
end_day_of_month int,
end_month int
)
The year is not included here just the day of month and month indices.
Your farmerfields table should then have a season_id column referring to this and most likely have a year column too.
Depending on your SQL vendor different date functions will be available but should should be able to compose a start and end date using the year from farmerfields and the month and day-of-month from season. Given this you can then determine if the current date falls within a given farmerfield entry's start and end dates.
I have an interesting query to do and am trying to find the best way to do it. Basically I have an absence table in our personnel database this records the staff id and then a start date and end date for the absence. End date being null if not yet entered (not returned). I cannot change the design.
They would like a report by month on number of absences (12 month trend). With staff being off over the month change it obviously may be difficult to calculate.
e.g. Staff off 25/11/08 to 05/12/08 (dd/MM/yy) I would want the days in November to go into the November count and the ones in December in the December count.
I am currently thinking in order to count the number of days I need to separate the start and end date into a record for each day of the absence, assigning it to the month it is in. then group the data for reporting. As for the ones without an end date I would assume null is the current date as they are presently still absent.
What would be the best way to do this?
Any better ways?
Edit: This is SQL 2000 server currently. Hoping for an upgrade soon.
I have had a similar issue where there has been a table of start/end dates designed for data storage but not for reporting.
I sought out the "fastest executing" solution and found that it was to create a 2nd table with the monthly values in there. I populated it with the months from Jan 2000 to Jan 2070. I'm expecting it will suffice or that I get a large pay cheque in 2070 to come and update it...
DECLARE TABLE months (start DATETIME)
-- Populate with all month start dates that may ever be needed
-- And I would recommend indexing / primary keying by start
SELECT
months.start,
data.id,
SUM(CASE WHEN data.start < months.start
THEN DATEDIFF(DAY, months.start, data.end)
ELSE DATEDIFF(DAY, data.start, DATEADD(month, 1, months.start))
END) AS days
FROM
data
INNER JOIN
months
ON data.start < DATEADD(month, 1, months.start)
AND data.end > months.start
GROUP BY
months.start,
data.id
That join can be quite slow for various reasons, I'll search out another answer to another question to show why and how to optimise the join.
EDIT:
Here is another answer relating to overlapping date ranges and how to speed up the joins...
Query max number of simultaneous events