View data by date after Format 'mmyy' - sql

I'm trying to answer questions like, how many POs per month do we have? Or, how many lines are there in every PO by month, etc. The original PO dates are all formatted #1/1/2013#. So my first step was to Format each PO record date into 'mmyy' so I could group and COUNT them.
This worked well but, now I cannot view the data by date... For example, I cannot ask 'How many POs after December did we get?' I think this is because SQL does not recognize mm/yy as a comparable date.
Any ideas how I could restructure this?
There are 2 queries I wrote. This is the query to format the dates. This is also the query I was trying to add the date filter to (ex: >#3/14#)
SELECT qryALL_PO.POLN, Format([PO CREATE DATE],"mm/yy") AS [Date]
FROM qryALL_PO
GROUP BY qryALL_PO.POLN, Format([PO CREATE DATE],"mm/yy");
My group and counting query is:
SELECT qryALL_PO.POLN, Sum(qryALL_PO.[LINE QUANTITY]) AS SUM_QTY_PO
FROM qryALL_PO
GROUP BY qryALL_PO.POLN;

You can still count and group dates, as long as you have a way to determine the part of the date you are looking for.
In Access you can use year and month for example to get the year and month part of the date:
select year(mydate)
, month(mydate)
, count(*)
from tableX
group
by year(mydate)
, month(mydate)

You can format it 'YYYY-MM' , and then use '>' for 'after' clause

Related

How to write SQL statement to select for data broken up for each month of the year?

I am looking for a way to write an SQL statement that selects data for each month of the year, separately.
In the SQL statement below, I am trying to count the number of instances in the TOTAL_PRECIP_IN and TOTAL_SNOWFALL_IN columns when either column is greater than 0. In my data table, I have information for those two columns ("TOTAL_PRECIP_IN" and "TOTAL_SNOWFALL_IN") for each day of the year (365 total entries).
I want to break up my data by each calendar month, but am not sure of the best way to do this. In the statement below, I am using a UNION statement to break up the months of January and February. If I keep using UNION statements for the remaining months of the year, I can get the answer I am looking for. However, using 11 different UNION statements cannot be the optimal solution.
Can anyone give me a suggestion how I can edit my SQL statement to measure from the first day of the month, to the last day of the month for every month of the year?
select monthname(OBSERVATION_DATE) as "Month", sum(case when TOTAL_PRECIP_IN or TOTAL_SNOWFALL_IN > 0 then 1 else 0 end) AS "Days of Rain" from EMP_BASIC
where OBSERVATION_DATE between '2019-01-01' and '2019-01-31'
and CITY = 'Olympia'
group by "Month"
UNION
select monthname(OBSERVATION_DATE) as "Month", sum(case when TOTAL_PRECIP_IN or TOTAL_SNOWFALL_IN > 0 then 1 else 0 end) from EMP_BASIC
where OBSERVATION_DATE between '2019-02-01' and '2019-02-28'
and CITY = 'Olympia'
group by "Month"```
Your table structure is too unclear to tell you the exact query you will need. But a general easy idea is to build the sum of your value and then group by monthname and/or by month. Sice you wrote you only want sum values greater 0, you can just put this condition in the where clause. So your query will be something like this:
SELECT MONTHNAME(yourdate) AS month,
MONTH(yourdate) AS monthnr,
SUM(yourvalue) AS yoursum
FROM yourtable
WHERE yourvalue > 0
GROUP BY MONTHNAME(yourdate), MONTH(yourdate)
ORDER BY MONTH(yourdate);
I created an example here: db<>fiddle
You might need to modify this general construct for your concrete purpose (maybe take care of different years, of NULL values etc.). And note this is an example for a MYSQL DB because you wrote about MONTHNAME() which is in most cases used in MYSQL databases. If you are using another DB type, maybe you need to do some modifications. To make sure that answers match your DB type, tag it in your question, please.

Display By month using select statement

SELECT SUM(Total_A ) FROM Materials_List
This is the snippet of code that I have.
I need it to calculate by month and display by month using SQL.
I also would like it to be a code I can use for any month in the year not just one month at a time.
You seem to be looking for simple aggregation:
select
year(materials_datetime) yr,
month(materials_datetime) mn,
sum(total_a) sum_total_a
from materials_list
group by
year(materials_datetime),
month(materials_datetime)
order by yr, mn
This assumes that column materials_datetime contains the date/time that you want to use to aggregate the data.

Teradata filter query to pull all data for a month

I have a query below which fetches me the data for last day of a month. In this query, ME_DT is defined as date time type. So when I do the max on ME_DT then it gives me the data for last day of a month. I think I need to convert the date time type to integer YYYYMM in a teradata filter condition, so that it gives me the data for the entire month not just for the last day of a month. How should I modify my existing query to get my desired result?
PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT =
(select max (PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT) from PADW.PL_CURR_DEFN_LOSS_FRCST_ME)
You should try to avoid calculations on a column in the WHERE-condition to get better estimates and possible index/partition-access:
with cte (dt) as
(
select max (PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT)
from PADW.PL_CURR_DEFN_LOSS_FRCST_ME
)
select ....
where PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT
between TRUNC(dt, 'mon')
and last_day(dt)
I have to use filer on the table because it has millions of records...
i did this ...but still verifying if I have got what i want...
(PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT =
(select max (cast(PADW.PL_CURR_DEFN_LOSS_FRCST_ME.ME_DT as date format 'YYYYMM')) from PADW.PL_CURR_DEFN_LOSS_FRCST_ME))

How to group by a date column by month

I have a table with a date column where date is stored in this format:
2012-08-01 16:39:17.601455+0530
How do I group or group_and_count on this column by month?
Your biggest problem is that SQLite won't directly recognize your dates as dates.
CREATE TABLE YOURTABLE (DateColumn date);
INSERT INTO "YOURTABLE" VALUES('2012-01-01');
INSERT INTO "YOURTABLE" VALUES('2012-08-01 16:39:17.601455+0530');
If you try to use strftime() to get the month . . .
sqlite> select strftime('%m', DateColumn) from yourtable;
01
. . . it picks up the month from the first row, but not from the second.
If you can reformat your existing data as valid timestamps (as far a SQLite is concerned), you can use this relatively simple query to group by year and month. (You almost certainly don't want to group by month alone.)
select strftime('%Y-%m', DateColumn) yr_mon, count(*) num_dates
from yourtable
group by yr_mon;
If you can't do that, you'll need to do some string parsing. Here's the simplest expression of this idea.
select substr(DateColumn, 1, 7) yr_mon, count(*) num_dates
from yourtable
group by yr_mon;
But that might not quite work for you. Since you have timezone information, it's sure to change the month for some values. To get a fully general solution, I think you'll need to correct for timezone, extract the year and month, and so on. The simpler approach would be to look hard at this data, declare "I'm not interested in accounting for those edge cases", and use the simpler query immediately above.
It took me a while to find the correct expression using Sequel. What I did was this:
Assuming a table like:
CREATE TABLE acct (date_time datetime, reward integer)
Then you can access the aggregated data as follows:
ds = DS[:acct]
ds.select_group(Sequel.function(:strftime, '%Y-%m', :date_time))
.select_append{sum(:reward)}.each do |row|
p row
end

SQL How to convert date DD-MM-YYYY to MM-YYYY and retrieve most recent records?

Hi I have to retrieve from my table most recent records that match a given MM-YYYY, but the date field in the table is DD-MM-YYYY, how do I get this done?
Thank you very much
Best Regards
Ignacio.
How many of the most recent records do you need?
Could you not query for all the dates in the relevant month, order by the dates, and then only select the results you need from the top of the list.
For example:
SELECT TOP(1) *
FROM your_table
WHERE date_time_field >= '20120101'
AND date_time_field < '20120201'
ORDER BY date_time_field DESC
This would select the most recent record from January of this year.
Change the number inside the TOP() statement to change the number of results returned, or leave it off altogether and take comfort in the fact that your results are ordered.
SELECT * FROM `your`.`schemaTableNames` WHERE your_coulumn_name LIKE "%-MM-YYYY";
should give you the matching records, as you wrote that you want to retrieve.
Have you tried using DateDiff(month, date1, date2) == 0 in your where clause?
This assumes that you can convert both values to DATETIME. If you only have the year and the month, every month has day 01.
to convert a date to desire format you can use style to retrive the records date formats
The following works:
right(select convert(varchar, <date field>, 110), 7)
The full query would look someting like this:
select *
from table
where right(select convert(varchar, <date field>, 110), 7) = 'MM-YYYY'