how to use group by with current year months and another data field in sequelize - sql

related table
I need GROUP BY createdAt's month and status in the current year using sequelize.
my expected output is:-
expected output

(might need to adjust syntax according to your db):
SELECT DATE_TRUNC('month', createdAt) as month,
status,
COUNT(id)
FROM table
GROUP BY 1, 2
If you really only want the month number use DATE_PART instead of DATE_TRUNC

Related

Get rows with timestamp from current week in Postgres?

I'm trying to build a weekly leaderboard of sorts and was wondering how I could get the rows with a timestamp that is within the current week (Monday to Sunday). I've tried:
SELECT id, COUNT(*) FROM Data WHERE created::date BETWEEN date $1 and date $2 GROUP BY id ORDER BY COUNT(*) DESC LIMIT 10;
But got stuck on how I could get the rows within the current week without hard coding them. created is a column of type TIMESTAMP.
I saw that there was something called YEARWEEK() in MySQL. Is there an equivalent in Postgres? If not, what can I do to get the desired result?
You can use date_trunc() with "week":
where created >= date_trunc('week', now())
This assumes that no created timestamps are in the future. Postgres follows the ISO standard of having weeks start on Mondays, which is what you want.

Why do i get a different results from my weekly code vs per week code?

Why am I getting different results when I compare weekly results into using a code individually per week. Does it have something to do with the timestamp?
This is the code for all the weeks:
select date_trunc('week',date_joined) as week, COUNT(*) as count from auth_user
where date_joined>='01-01-2019' and date_joined<='31-03-2019'
group by week
order by week
This is the resulting table:
first result
This is the code for getting an individual week:
select COUNT(*) from auth_user where date_joined>='31-12-2018' and date_joined<='06-01-2019'
This is the result for the first week: second result
I'd say that date_joined is a timestamp, and your second query misses the entries from January 6th.
Try with
AND date_joined < '2019-01-07'
Also, you should use ISO notation: YYYY-MM-DD

How to get last and first date of every week from predefined date table (oracle SQL)

I have Table D_date in which all dates of a year, week number,quarter number etc attributes are defined. I just want to get first and last date of every week of year 2015.
Sample D_date tabe attached.
It is simple min/max if I understand you right
SELECT calendar_year_nbr, week, min(actual_date),max(actual_date)
FROM D_date
GROUP BY calendar_year_nbr, week
I just want to get first and last date of every week of year 2015.
Since you have precomputed values already stored in the table, you could directly use MIN and MAX as aggregate functions along with GROUP BY.
For example,
SELECT MIN(actual_date) min_date,
MAX(actual_date) max_date,
calendar_week_nbr
FROM d_date
WHERE calendar_year_nbr = 2015
GROUP BY calendar_week_nbr
ORDER BY min_date;
Another way is to use ROWNUM() OVER() analytic function.

use of week of year & subsquend in bigquery

I need to show distinct users per week. I have a date-visit column, and a user id, it is a big table with 1 billion rows.
I can change the date column from the CSVs to year,month, day columns. but how do I deduce the week from that in the query.
I can calculate the week from the CSV, but this is a big process step.
I also need to show how many distinct users visit day after day, looking for workaround as there is no date type.
any ideas?
To get the week of year number:
SELECT STRFTIME_UTC_USEC(TIMESTAMP('2015-5-19'), '%W')
20
If you have your date as a timestamp (i.e microseconds since the epoch) you can use the UTC_USEC_TO_DAY/UTC_USEC_TO_WEEK functions. Alternately, if you have an iso-formatted date string (e.g. "2012/03/13 19:00:06 -0700") you can call PARSE_UTC_USEC to turn the string into a timestamp and then use that to get the week or day.
To see an example, try:
SELECT LEFT((format_utc_usec(day)),10) as day, cnt
FROM (
SELECT day, count(*) as cnt
FROM (
SELECT UTC_USEC_TO_DAY(PARSE_UTC_USEC(created_at)) as day
FROM [publicdata:samples.github_timeline])
GROUP BY day
ORDER BY cnt DESC)
To show week, just change UTC_USEC_TO_DAY(...) to UTC_USEC_TO_WEEK(..., 0) (the 0 at the end is to indicate the week starts on Sunday). See the documentation for the above functions at https://developers.google.com/bigquery/docs/query-reference for more information.

Group by month and year in MySQL

Given a table with a timestamp on each row, how would you format the query to fit into this specific json object format.
I am trying to organize a json object into years / months.
json to base the query off:
{
"2009":["August","July","September"],
"2010":["January", "February", "October"]
}
Here is the query I have so far -
SELECT
MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM
trading_summary t
GROUP BY MONTH(t.summaryDateTime) DESC";
The query is breaking down because it is (predictably) lumping together the different years.
GROUP BY YEAR(t.summaryDateTime), MONTH(t.summaryDateTime);
is what you want.
GROUP BY DATE_FORMAT(summaryDateTime,'%Y-%m')
I prefer
SELECT
MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM
trading_summary t
GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime);
I know this is an old question, but the following should work if you don't need the month name at the DB level:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month;
See EXTRACT function docs
You will probably find this to be better performing.. and if you are building a JSON object in the application layer, you can do the formatting/ordering as you run through the results.
N.B. I wasn't aware you could add DESC to a GROUP BY clause in MySQL, perhaps you are missing an ORDER BY clause:
SELECT EXTRACT(YEAR_MONTH FROM summaryDateTime) summary_year_month
FROM trading_summary
GROUP BY summary_year_month
ORDER BY summary_year_month DESC;
SELECT MONTHNAME(t.summaryDateTime) as month, YEAR(t.summaryDateTime) as year
FROM trading_summary t
GROUP BY YEAR(t.summaryDateTime) DESC, MONTH(t.summaryDateTime) DESC
Should use DESC for both YEAR and Month to get correct order.
You must do something like this
SELECT onDay, id,
sum(pxLow)/count(*),sum(pxLow),count(`*`),
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate
FROM ... where stockParent_id =16120 group by sdate order by onDay
This is how I do it:
GROUP BY EXTRACT(YEAR_MONTH FROM t.summaryDateTime);
use EXTRACT function like this
mysql> SELECT EXTRACT(YEAR FROM '2009-07-02');
-> 2009
You cal also do this
SELECT SUM(amnt) `value`,DATE_FORMAT(dtrg,'%m-%y') AS label FROM rentpay GROUP BY YEAR(dtrg) DESC, MONTH(dtrg) DESC LIMIT 12
to order by year and month. Lets say you want to order from this year and this month all the way back to 12 month
You are grouping by month only, you have to add YEAR() to the group by
SELECT YEAR(t.summaryDateTime) as yr, GROUP_CONCAT(MONTHNAME(t.summaryDateTime)) AS month
FROM trading_summary t GROUP BY yr
Still you would need to process it in external script to get exactly the structure you're looking for.
For example use PHP's explode to create an array from list of month names and then use json_encode()
As this data is being pulled for a trade summary by month, I had to do the same thing and would just like to add the code I use. The data I have is saved in the database as a string so your query may be simpler. Either way, as a trader, this is in essence what most people would be looking for:
select
DATE(DATE_FORMAT(STR_TO_DATE(closeDate, '%Y-%m-%d'), '%Y-%m-01')) AS month_beginning,
COUNT(*) AS trades,
TRUNCATE(sum(profitLoss)/count(*),2) as 'avgProfit',
TRUNCATE(sum(percentGain)/count(*),2) as 'avgPercent',
sum(profitLoss) as 'gi',
sum(profitLoss > 0)/count(*) AS winPercent,
sum(profitLoss < 0)/count(*) as 'lossPercent',
max(profitLoss) as bigWinner,
min(profitLoss) as bigLoser
from tradeHistory
group by month_beginning
order by month_beginning DESC
However, it will skip months that are missing in your data. So if there is no data for Jan, there won't be a row.
I would like add difference between group by year(datetime),month(datetime) and groupb by extract(year_month from datetime).
here is the query i tried with these two cases.
select year(datetimecol) as Year,monthname(datetimecol) as Month from table
group by year(datetimecol) and month(datetimecol) order by year(datetimecol) desc;
result:
Year, Month
2020, May
select year( datetimecol) as Year,monthname(datetimecol) as Month from table
GROUP BY EXTRACT(YEAR_MONTH FROM datetimecol) order by year(datetimecol) desc,month(datetimecol) asc;
result:
Year, Month
2021, January
2021, February
2021, March
2021, April
2021, May
2020, May
2020, June
2020, July
2020, August
2020, September
2020, October
2020, November
2020, December
(this is the result i need)
My observation
1.when i am using with group by year(datetimecol),month(datetimecol) , not giving desired result ..might be because of datetime feild...
2.when i tired second query with GROUP BY EXTRACT(YEAR_MONTH FROM datetimecol) order by year(datetimecol)...its working absolutely fine.
in conclusion, for getting months by year wise use the following query.
select year( datetimecol) as Year,monthname(datetimecol) as Month from table
GROUP BY EXTRACT(YEAR_MONTH FROM datetimecol) order by year(datetimecol) desc,month(datetimecol) asc;
Use
GROUP BY year, month DESC";
Instead of
GROUP BY MONTH(t.summaryDateTime) DESC";