I have a 2 year data in SQL and i want to create or write query will be pull out data monthly basis. How do i write query which will give me every month data in one shot.
Jan Feb Mar Apil ....etc
SELECT myField1,myField2,...MONTH(myDateField) as monthDate,YEAR(myDateField) as yearDate
FROM myTableName ORDER BY yearDate,monthDate
Related
I have the following query that pulls all records from a Redshift table from January 1st of the current year through the final date of the most recent, full quarter.
SELECT *
FROM table
WHERE date_value BETWEEN DATE_TRUNC('year',getdate()) AND DATE_TRUNC('quarter',dateadd(day,-1,getdate()));
I now want to create a period-over-period comparison query that returns all records for the previous n months. Ex. if the first query returns all records for Jan - Jun 2022, this query will return all records for Jul - Dec 2021.
Here is what I have so far, however it currently returns Jan - Jun 2021 instead of the desired date range. I've tried playing around with DATEDIFF() instead of DATEADD() but haven't had any luck with that either. Any help is much appreciated.
SELECT *
FROM TABLE
WHERE date_value BETWEEN DATE_TRUNC('year',dateadd(year,-1,getdate())) AND DATE_TRUNC('quarter',dateadd(year,-1,getdate()));
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.
I have a simple statement that starts:
SELECT a.product, MONTH(a.saledate) AS Month, Count(*) AS Total
Which yields, for example,
Product Month Total
Bike 8 1000
Please can anyone advise if it's possible to add the month's name to this query and also, is it possible to get a monthly total to appear as well?
Thanks!
The query in your example counts all the rows in your table, then presents that count next to a randomly chosen row's product and sale date. That's -- almost certainly -- not what you want. MySQL is quirky that way. Other DBMSs reject your example query.
If you want to display a monthly summary of product sold, here's the basic query:
SELECT a.product,
LAST_DAY(a.saledate) AS month_ending,
COUNT(*) AS Total
FROM table a
GROUP BY a.product, LAST_DAY(a.saledate)
The LAST_DAY() function is a great way to extract month and year from a date.
Finally, if you want to display the text name of the month, you can use the DATE_FORMAT() function to do that. %b as a format specifier gives a three-letter month name, and %M gives the full month name. So this query will do it.
SELECT a.product,
LAST_DAY(a.saledate) AS month_ending,
DATE_FORMAT(LAST_DAY(a.saledate), '%M %Y')) AS month
COUNT(*) AS Total
FROM table a
GROUP BY a.product, LAST_DAY(a.saledate)
In SQL Server 2012+ you can use the EOMONTH() function in place of LAST_DAY().
In SQL Server 2008+ you can use DATENAME(mm, a.saledate) to retrieve the month name from a date.
There are two ways of getting month name
1)
SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (MONTH(a.saledate) * 4) - 3, 3)
2)
DATENAME(month, a.saledate)
Some poeple say You might be using MYSQL:
Then getting month name will be:
SELECT MONTHNAME( a.saledate);
I would like to get a running tally of how many widgets were/are rented at any one time, by month, by year. Data is held in an MS Access 2003 db;
Table name: rent_table
Fields:
rentid
startdate
enddate
rentfee
rentcost
bookingfee
Something like; Count number of rentid's that fall between month/year, then group them?
e.g. if a widget was rented from 5th Jan 2014 to 8th April 2014 it would appear as a count in Jan, Feb, Mar and April tally's.
Many thanks.
EDIT
More details (sorry);
Access db is fronted by classic ASP.
If possible I don't want to create any new tables.
No input is required in order to run the report.
There are around 350-400 widgets that could be rented at any one time.
Each widget is rented exclusively.
Report output example;
Month | Year | NumRented
Jan 2014 86
Feb 2014 113
...
Can a query pick up dates within dates? So literally do a count of the table where date >Dec 31st 2013 AND <1st Feb 2014 (to grab a count for all of January 2014) and would that include the example of the rent starting on the 5th Jan? So I could just do twelve counts for each year?
create a calendar table, e.g.
table = cal_yyyymm with one column dt_yyyymm as numeric field
populate the table with ... say 5 or 10 years of data
201401 201402 201403 ... 60 or 120 rows, a small table
make a sql
Select
dt_yyyymm,
count(*) as cnt
From cal_yyyymm
Left Join rent_table
On format(startdate,"yyyymm") >= dt_yyyymm
And dt_yyyymm >= format(enddate,"yyyymm")
think about the complications in the data -- --
widget was rented from 5th Jan 2014 to 8th Jan 2014
and again rented from 11th Jan 2014 to 21st Jan 2014
does this count at 1 or 2 in the month?
if it is 1, then the sql gets more complicated because
the rent_table first needs to have its dates converted
to yyyymm format, and second needs to be de-duped on rentid,
and third then joined to cal_ On the dates...
In SSRS 2005, I need to provide a drop down to the user with month year labels for the last two months.
For e.g. Jan 2010, Feb 2010, ... , Jan 2011, .... Dec 2011
I need this dynamically for the last two years (say).
Additionally, as user select one of the label, I need to pass the last date of the selected month-year combination to the query parameter.
Please help!
Sijoy
Assuming you are reporting from a SQL datasource, create a new dataset with a query to return the last date of each month within the required range (ie. the last two months) and the month-year description of each month - the details of the query will vary depending on the SQL database (MySQL, SQLServer, Oracle, etc). Populate the parameter from this new dataset, and set the value to be the date field and the label to be the description field.