GROUP BY month and year - SQLite - sql

I got the following SQLite database:
What I'm trying to do is: sum all values based on quantidade grouped by Month/Year (e.g.: 2022/08)
The result I'm expecting grouped by year/month:
My SQL code:
SELECT
data, SUM(quantidade) AS sum
FROM stock_tracking_Negociacao
WHERE mercado = 'Futuro'
GROUP BY strftime('%Y', data), strftime('%m', data)
Any help?

We can use SUBSTR() here to isolate the month and year, then aggregate:
SELECT SUBSTR(data, 4, 7) AS ym, SUM(quantidade) AS sum
FROM stock_tracking_Negociacao
WHERE mercado = 'Futuro'
GROUP BY 1;
Note that SQLite does not have a formal date type, but rather stores dates as strings.

For SQLite the only valid text-based date format is YYYY-mm-dd.
When you use any other format with date functions like strftime() the result is null and this is the main reason that your code does not work.
Since you mention that in the database the dates have the format YYYY/mm/dd you can update to the correct format:
UPDATE stock_tracking_Negociacao
SET data = REPLACE(data, '/', '-');
and then your query should be:
SELECT strftime('%Y-%m', data) AS year_month,
SUM(quantidade) AS sum
FROM stock_tracking_Negociacao
WHERE mercado = 'Futuro'
GROUP BY year_month;

Related

How to convert an int to DateTime in BigQuery

I have an INT64 column called "Date" which contains many different numbers like: "20210209" or "20200305". I want to turn those numbers into a date with this format: MM-YYYY (so in these cases, 02-2021 and 03-2020). Ultimately I want to sum all the data in each month together. The problem is that BigQuery can't convert INT64 to date, only to strings. I'm not sure if I should convert to a string and then to a date or if there is a better way.
Although converting to a string then a date both works and is very concise, over large enough numbers of rows (which may be the case in Big Query) you may be better off using integer maths and using DATE(year, month, day)...
https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date
SELECT
DATE(
DIV( 20210209 , 10000), -- Which gives 2021
DIV(MOD(20210209, 10000), 100), -- Which gives 02
MOD(20210209, 100) -- Which gives 09
)
You can convert the value to a string and use parse_date():
select parse_date('%Y%m%d', cast(20210209 as string))
Another option
select date,
regexp_replace('' || date, r'(\d{4})(\d{2})(\d{2})', r'\2-\1') as MM_YYYY
from your_table
if applied to sample data in your question - output is
Yet another option
select date,
format_date('%m-%Y', parse_date('%Y%m%d', '' || date)) as MM_YYYY
from your_table
with same output

SQL statement for how to return date and sales revenue

I am trying to run a SQL query to return my total sales of the day and date (yyyy-mm-dd format). I am running the code where filter_dailysales = (input date here) variable but it is not working.
SELECT TO_CHAR(Orders_OrderTimeStamp, 'yyyy-mm-dd'), SUM(Orders_Price)
FROM Orders
WHERE TO_CHAR(Orders_OrderTimeStamp, 'yyyy-mm-dd') = '"+str(filter_dailysales)+"')
So I have table Orders with columns Orders_ID, Orders_OrderTimeStamp, Orders_Price
I have inputed code like this using cx_oracle on python
c.execute("insert into orders values ('9', 1.7, sysdate-31, 9, sysdate-31, '2', '1', '3')")
My desired result output would be first column: Date selected with an input variable, second column: The aggregated sum of orders_price. The results would just be one row.
Try adding a group by to your query. Something like:
SELECT TO_CHAR(Orders_OrderTimeStamp, 'yyyy-mm-dd')
, SUM(Orders_Price)
FROM Orders
WHERE TO_CHAR(Orders_OrderTimeStamp, 'yyyy-mm-dd') = '"+str(filter_dailysales)+"')
GROUP BY TO_CHAR(Orders_OrderTimeStamp, 'yyyy-mm-dd')
Also, use bind variables instead of string substitution where possible. See:
https://blogs.oracle.com/sql/improve-sql-query-performance-by-using-bind-variables

How to convert an YYYY-MM-DD date to YYYY-MM date

In SQL. How to convert a column A from (YYYY-MM-DD) to (YYYYMM)? I want to show the dates in YYYYMM format instead of YYYY-MM-DD.
Data type is TIMESTAMP. Using Teradata Studio 15.10.10.
For Teradata either use
to_char(tscol, 'YYYYMM') -- varchar result
or
extract(year from tscol) * 100 + extract(month from tscol) -- integer result
In Teradata you can format dates pretty much at will. To get YYYYMM, you would use
select <your date> (format 'yyyymm') (char(6))
Your date column needs to be actual date for this, not a string.
There are 3 functions you'll need.
MONTH() function. Returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0.
YEAR() function. Returns a 4 digit YEAR.
CONCAT() function is used to concatenate two or more strings together.
So here's an example of combining the 3 functions.
SELECT CONCAT(YEAR('1969-02-18'),MONTH('1969-02-18'))
or you can do it in one with
select DATE_FORMAT('1969-02-18','%Y%m')
So to answer your question if it is referring to column A, you can use
SELECT DATE_FORMAT(A,'%Y%m')
SQL Fiddle:
http://www.sqlfiddle.com/#!9/a6c585/48362
You can use DATEPART to get the year and month parts of the date, cast to a varchar, pad and the concaternate.
SELECT DATEPART(YEAR,GETDATE())
SELECT DATEPART(MONTH,GETDATE())
SELECT CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR(4)) + RIGHT('00' + CAST(DATEPART(MONTH,GETDATE()) AS VARCHAR(2)),2)

Selecting YYYYMM of the previous month in HIVE

I am using Hive, so the SQL syntax might be slightly different. How do I get the data from the previous month? For example, if today is 2015-04-30, I need the data from March in this format 201503? Thanks!
select
employee_id, hours,
previous_month_date--YYYYMM,
from
employees
where
previous_month_date = cast(FROM_UNIXTIME(UNIX_TIMESTAMP(),'yyyy-MM-dd') as int)
From experience, it's safer to use DATE_ADD(Today, -1-Day(Today)) to compute last-day-of-previous-month without having to worry about edge cases. From there you can do what you want e.g.
select
from_unixtime(unix_timestamp(), 'yyyy-MM-dd') as TODAY,
date_add(from_unixtime(unix_timestamp(), 'yyyy-MM-dd'), -1-cast(from_unixtime(unix_timestamp(), 'd') as int)) as LAST_DAY_PREV_MONTH,
substr(date_add(from_unixtime(unix_timestamp(), 'yyyy-MM-dd'), -1-cast(from_unixtime(unix_timestamp(), 'd') as int)), 1,7) as PREV_MONTH,
cast(substr(regexp_replace(date_add(from_unixtime(unix_timestamp(), 'yyyy-MM-dd'), -1-cast(from_unixtime(unix_timestamp(), 'd') as int)), '-',''), 1,6) as int) as PREV_MONTH_NUM
from WHATEVER limit 1
-- today last_day_prev_month prev_month prev_month_num
-- 2015-08-13 2015-07-30 2015-07 201507
See Hive documentation about date functions, string functions etc.
below works across year boundaries w/o complex calcs:
date_format(add_months(current_date, -1), 'yyyyMM') --previous month's yyyyMM
in general,
date_format(add_months(current_date, -n), 'yyyyMM') --previous n-th month's yyyyMM
use proper sign for needed direction (back/ahead)
You could do (year('2015-04-30')*100+month('2015-04-30'))-1 for the above mentioned date, it will return 201503 or something like (year(from_unixtime(unix_timestamp()))*100+month(from_unixtime(unix_timestamp())))-1 for today's previous month. Assuming your date column is in 'yyyy-mm-dd' format you can use the first example and substitute the date string with your table column name; for any other format the second example will do, add the column name in the unix_timestamp() operator.
Angelo's reply is a good start but it returns 201500 if the original date was 2015-01-XX. Building on his answer, I suggest using the following:
IF(month(${DATE}) = 1,
(year(${DATE})-1)*100 + 12,
year(${DATE})*100 + month(${DATE})-1
) as month_key
provided you get rid of those hyphens in your input string , previous date's month id in YYYYMM format you can get by:-
select if( ((${hiveconf:MonthId}-1)%100)=0 ,${hiveconf:MonthId}-89,${hiveconf:MonthId}-1 ) as PreviousMonthId;

Getting only day and month from a date field

I have a set of dates that are in the format DD-MMM-YYYY. I need to be able to compare dates by using only the DD-MMM part of the date, since the year isn't important.
How would I achieve this?
I have tried reading up on the DATEPART function (edit: which evidently wouldn't work) but I can only theoretically get that to return either the DD or the MMM parts, not both of them at once.
Edit: added oracle tag. Sorry.
Example of date field: 01-MAR-1994
If your column is of type DATE then it doesn't have a format.
If I understand you right, then you want to view the mon-dd part only, so you need to convert it with TO_CHAR function,
i.e.:
select to_char(your_date_column, 'mon-dd') from your_table
Convert your dates using the following format, it will only month and the date part. You have to replace getdate() with you date fields.:
select convert(varchar(5),getdate(),110)
Assuming that you are using SQL Server or Oracle since you attempted using DATEPART, you can just get the day and month using the DAY() and MONTH() functions. Assuming, again, that the dates you are comparing are in two different tables, it would look similar to this:
SELECT MONTH(t1.date), DAY(t2.date)
FROM table AS t1
INNER JOIN table2 AS t2
ON t1.key = t2.key
WHERE MONTH(t1.date) = MONTH(t2.date)
AND DAY(t1.date) = DAY(t2.date)
EDIT: If you are just comparing rows in the same table, you only need a very simple query.
SQLFiddle
select id, TO_CHAR(most_recent, 'mon-dd')
from (
select id, MAX(date1) AS most_recent
from table1
group by id
)
You can also combine month and day into one integer:
EXTRACT(MONTH FROM datecol) * 100 + EXTRACT(DAY FROM datecol) AS MonthDay
Then it's easier to sort and compare.
select FORMAT(yourcoulmn_name, 'dd/MM') from table
This should do the trick
`select CONVERT(varchar(7),datetime_column,100) from your_table`
date_default_timezone_set("Asia/Kolkata");
$m = date("m");//Month
$d = date("d");//Day
$sql = "SELECT * FROM contactdata WHERE MONTH(date) = '$m' AND DAY(date) = '$d' ";
only checks day and month and returns today, day and month from database
SELECT LEFT(REPLACE(CONVERT(varchar(10),GETDATE()-1,3),'/',''),4)
WOuld this work for you?
FROMAT(DATETIME, 'dd-MMM') = FROMAT(DATETIME, 'dd-MMM') use any format you want