Count and a Sum in the same query? - mysql

so i have a query that works which gives the sum cost:
SELECT ROUND(SUM(cost), 2) AS 'Sum of Cost',
MONTH(startDateTime) AS Month,
MONTHNAME(STR_TO_DATE(MONTH(startDateTime), '%m')) month_name
FROM Event
GROUP BY Month;
The other thing I wanted to add to this query was the amount of times that an event took place in each month as their are a few months that have events on the same days thus affecting the total sum of the events.

Due you're grouping by month, you can use both, SUM and COUNT in the same sentence.
SELECT ROUND(SUM(cost), 2) AS 'Sum of Cost',
MONTH(startDateTime) AS Month,
MONTHNAME(STR_TO_DATE(MONTH(startDateTime), '%m')) month_name,
COUNT(*) as NumEvents
FROM Event
GROUP BY MONTH(startDateTime);

first off update your group by.. accordingly to Logical order
SELECT ROUND(SUM(cost), 2) AS 'Sum of Cost', MONTH(startDateTime) AS Month
FROM Event
GROUP BY MONTH(startDateTime);

Related

Incrementing MySql variable by SUM() not correct

I am trying to put together a query that groups records by date along with a total for that particular date (there can be multiple entries in a day) but I also need a running total that I intended on using a MySQL variable for. My issue is that the cumulative total column seems to contain the SUM() for just that date.
So this works fine for the daily totals
SELECT
YEAR(log_at) as year,
MONTH(log_at) as month,
DAY(log_at) as day,
SUM(ev) as dailyTotal,
count(*) as count
FROM tracks
WHERE user_id = 1
GROUP BY year, month, day
ORDER BY year, month, day ASC
Add what I thought was going to be a fairly simple variable in there to keep track of the running total
SET #cumulative := 0;
SELECT
YEAR(log_at) as year,
MONTH(log_at) as month,
DAY(log_at) as day,
SUM(ev) as dailyTotal,
#cumulative := #cumulative + sum(ev) AS cumulative,
count(*) as count
FROM tracks
WHERE user_id = 1
GROUP BY year, month, day
ORDER BY year, month, day ASC
And the cumulative variable just contains the total for that day. But if I change it to increment by 1 instead of the SUM() it seems to work correctly
Any advice for achieving the desired behaviour is greatly appreciated!
You have to first create the whole selection and only then do your cumulative-stuff because you can't append the sum of a column of your GROUP BY at the same time (I don't really know why dough)
SELECT
`year`,
`month`,
`day`,
`dailyTotal`,
#cum := #cum + `dailyTotal` as `cumulative`,
`count`
FROM
(
SELECT
YEAR(log_at) as year,
MONTH(log_at) as month,
DAY(log_at) as day,
SUM(ev) as dailyTotal,
count(*) as count
FROM tracks
WHERE user_id = 1
GROUP BY year, month, day
ORDER BY year, month, day ASC
) a
JOIN (SELECT #cum := 0) b
I tested it with a bit less intensive tables... maybe I got this one wrong here. But I hope you get the theory.

Number of logins during hourly, each day of the week?

I have a list of data contians (yyyy-mm-dd, hh:min:ss) from this data i need to sort out how many times 'logins' was punched for any given hour of the day. and also how many times logins' was punched for each day of the week .
I tried some code but am not confident the code i have right. Also should i include COUNT(*) in the statement
This code for hourly logins :
SELECT date_time, HOUR(date_time) FROM time_logs ORDER BY DAY(date_time);
Code for day for week:
SELECT date_time, DAY(date_time) FROM time_logs ORDER BY DAY(date_time);
Is this is right. If not could you give me hint
To count how many logins per hour, you just need to add COUNT(*) in your SELECT and GROUP BY HOUR(date_time).
SELECT date_time, HOUR(date_time),COUNT(*) 'Total Logins'
FROM time_logs GROUP BY HOUR(date_time) ORDER BY DAY(date_time);
Similarly on your day count you need to add the same thing. Only difference is your grouping is now by day.
SELECT date_time, DAY(date_time), COUNT(*) 'Total Logins'
FROM time_logs GROUP BY DAY(date_time) ORDER BY DAY(date_time);
You can cast your datetime to both hour and date and then group by to get your aggregations.
https://rextester.com/BQSV80644
For hour of the day:
SELECT HOUR(date_time), COUNT(*)
FROM time_logs
GROUP BY HOUR(date_time);
For day of the week:
SELECT WEEKDAY(date_time), COUNT(*)
FROM time_logs
GROUP BY WEEKDAY(date_time)
ORDER BY MIN(date_time)

Mysql picking the greatest columna after aggregation

I have a table of sold items, with specified name, day, hour and amount of items sold.
What I need to do is for every day find the hour in which the greatest number of items (of any type) was sold and return the two-columned table with day and amount of items.
What I managed to do is to compute the sum of items per hour, but how to pick the hour with maximum amount of items sold and show it together with the day?
here is my lousy sqlfiddle attempt: http://sqlfiddle.com/#!9/93b51/17/0
select day, hour, sum(amount) as suma
from sold_items
group by day, hour
You need to join your query with juergen d's query that gets the maximum hourly amount each day.
SELECT a.day, a.hour, a.suma
FROM (
select day, hour, sum(amount) as suma
from sold_items
group by day, hour) AS a
JOIN (
select day, max(suma) AS maxsuma
from (
select day, hour, sum(amount) as suma
from sold_items
group by day, hour) AS tmp
group by day) AS b
ON a.day = b.day AND a.suma = b.maxsuma
DEMO
This follows the same pattern as SQL Select only rows with Max Value on a Column except that in this case, you're doing it with a subquery that calculates an aggregate, not the data coming directly from the table.
select day, max(suma)
from
(
select day, hour, sum(amount) as suma
from sold_items
group by day, hour
) tmp
group by day
SQLFiddle

MySQL group by day with datetime mixing same dates from different months

I'm trying to group posts from same day, the problem is that 2/20 gets grouped with 3/20 (20 = 20)
How can this be fixed?
This is my current code:
select day(Date), count(*) from Posts WHERE shopID != '' group by shopID, day(Date)
You need to group by every piece that might be different. So add MONTH(Date) and even YEAR(Date) depending on the scope of your query.
select DAY(Date), count(*) from Posts WHERE shopID != '' group by shopID, YEAR(Date), MONTH(Date), DAY(Date)
You could also group this way: UNIX_TIMESTAMP(date(date)), instead of grouping by year, month and day separately
select date(date), count(*) from Posts
WHERE shopID != ''
group by shopID, UNIX_TIMESTAMP(date(date))
Note you'll have to also take the other date data in the select statement to be able to recognize which month/year the day belongs to. If you don't you'll get a lot of day numbers and counts, but the day numbers will be repeated for each month/year.
That's why I used date(date), count(*).

MySQL SUM IF field b = field a

SELECT
incMonth as Month,
SUM( IF(item_type IN('typ1', 'typ2') AND incMonth = Month, 1, 0 ) )AS 'Total Sales'
FROM tester
I just need the sum for the current month its looping through.
If I'm reading that right, you'd need to use a group-by or at least a where clause to restrict things to just the time range you're wanting:
SELECT incMonth AS Month, SUM(IF(item_type IN('typ1', 'typ2'), 1, 0)) AS 'Total Sales'
FROM tester
GROUP BY incMonth