I have these two tables (times and sales):
times
TIME_ID | DAY_NAME | DAY_NUMBER_IN_WEEK | CALENDAR_MONTH_NAME | CALENDAR_MONTH_ID
1998-01-10| Monday | 1 | January | 1684
1998-01-10| Tuesday | 2 | January | 1684
1998-01-10| Wednesday | 3 | January | 1684
...
1998-01-11| Monday | 1 | February | 1685
1998-01-11| Tuesday | 2 | January | 1685
1998-01-11| Wednesday | 3 | January | 1685
sales
PROD_ID | TIME_ID | AMOUNT_SOLD
13 | 1998-01-10 | 1232
13 | 1998-01-11 | 1233
14 | 1998-01-11 | 1233
I need to make columns for every day in week (Monday, Tuesday, Wednesday...) and SUM of AMOUNT_SOLD for each PROD_ID for each day for each month.
SELECT SUM(times.day_number_in_week), times.calendar_month_name, times.day_name, times.calendar_year
FROM sales
INNER JOIN times ON times.time_id = sales.time_id
GROUP BY times.calendar_month_number, times.calendar_month_name, times.day_name, times.calendar_year
Output:
5988 March Wednesday 1998
9408 April Thursday 1998
7532 June Sunday 1998
9220 July Thursday 1998
7490 July Sunday 1998
12540 August Saturday 1998
but this sum all Wednesdays for all years, i need sum of amount for 1 month for all days (Wednesday, Monday...) for one month.
Can you help me?
You can do conditional aggregation:
SELECT
t.calendar_year
t.calendar_month_name,
SUM(case when t.day_number_in_week = 1 then s.amount_sold else 0 end) amount_sold_mon,
SUM(case when t.day_number_in_week = 2 then s.amount_sold else 0 end) amount_sold_tue,
SUM(case when t.day_number_in_week = 3 then s.amount_sold else 0 end) amount_sold_wed,
...
FROM sales s
INNER JOIN times t ON t.time_id = sales.time_id
GROUP BY t.calendar_year, t.calendar_month_number, t.calendar_month_name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.