Get SUM of values in a column after query is ran - mysql

This is my SQL statement which pulls back all the fills I've had in a certain time frame. Is there a way to get the list to come up and also pull the SUM of all of them?
SELECT customerName, date, gallons
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
ORDER BY CONVERT(DATE, date) ASC

First, I would write your query as:
SELECT customerName, date, gallons
FROM addFill
WHERE date >= '2015-03-03'
ORDER BY date ASC;
I see no value in ordering by the date and not the date/time component. Also, you might as well just use a recognizable date format for the comparison.
If you want the sum as well, then that is tricky. One method uses rollup:
SELECT customerName, date, SUM(gallons) as gallons
FROM addFill
WHERE date >= '2015-03-03'
GROUP BY customerName, date with rollup

sums of fills per customer since '3-3-2015'
SELECT customerName, date, sum(gallons)
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
GROUP BY customerName
sum of fills for all customers since '3-3-2015'
SELECT sum(gallons)
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )

Related

Avg function not returning proper value

I expect this query to give me the avg value from daily active users up to date and grouped by month (from Oct to December). But the result is 164K aprox when it should be 128K. Why avg is not working? Avg should be SUM of values / number of current month days up to today.
SELECT sq.month_year AS 'month_year', AVG(number)
FROM
(
SELECT CONCAT(MONTHNAME(date), "-", YEAR(DATE)) AS 'month_year', count(distinct id_user) AS number
FROM table1
WHERE date between '2020-10-01' and '2020-12-31 23:59:59'
GROUP BY EXTRACT(year_month FROM date)
) sq
GROUP BY 1
Ok guys thanks for your help. The problem was that on the subquery I was pulling the info by month and not by day. So I should pull the info by day there and group by month in the outer query. This finally worked:
SELECT sq.day_month, AVG(number)
FROM (SELECT date(date) AS day_month,
count(distinct id_user) AS number
FROM table_1
WHERE date >= '2020-10-01' AND
date < '2021-01-01'
GROUP BY 1
) sq
GROUP BY EXTRACT(year_month FROM day_month)
Do not use single quotes for column aliases!
SELECT sq.month_year, AVG(number)
FROM (SELECT CONCAT(MONTHNAME(date), '-', YEAR(DATE)) AS month_year,
count(distinct id_user) AS number
FROM table1
WHERE date >= '2020-10-01' AND
date < '2021-01-01'
GROUP BY month_year
) sq
GROUP BY 1;
Note the fixes to the query:
The GROUP BY uses the same columns as the SELECT. Your query should return an error (although it works in older versions of MySQL).
The date comparisons have been simplified.
No single quotes on column aliases.
Note that the outer query is not needed. I assume it is there just to illustrate the issue you are having.

Mysql. Change date format output on GROUP BY DAY query

I execute this query
SELECT * FROM graph WHERE ean IN ('00000000166330') group by DAY(created_at);
Getting those results:
# id, ean, avg_price, created_at
'58', '00000000166330', '2799.0000', '2020-06-11 16:43:27'
I want to change the date format returned of the created_at field.
I would like to get only the date, not the hour, and with the format: Day, month, Year.
My guess is that DATE_FORMAT should be used, but how to use it, grouping also by day?
Example here
You are not doing any aggregation, so remove group by
You can replace the operator IN with = because you are comparing against 1 value only
Use the function DATE() to get only the date part from created_at
You need a correlated subquery in the WHERE clause to get the row with the minimum id (since it does not matter whic row will be returned) of each day:
SELECT g.id, g.ean, g.avg_price, DATE_FORMAT(g.created_at, '%d-%m-%Y') created_at
FROM graph g
WHERE g.ean = '00000000166330'
AND g.id = (SELECT MIN(id) FROM graph WHERE ean = g.ean AND DATE(created_at) = DATE(g.created_at))
See the demo.
If you want distinct values without aggregation function you should use DISTINCT and for date you can use the date_format() function
SELECT DISTINCT DAY(created_at)
, date_format(date(created_at),'%d, %m, %Y') , id, avg_price
FROM graph WHERE ean = '00000000166330';
and when you have only a value you should use = and not IN operator.

Order by date when a format 'dd-MM-YYYY' is given in the select statement is not working as expected

I store the date in a DATETIME field in my database. When I create a select statement I need to show it with format '%d-%m-%Y' but I have problems sorting the data by date.
this is my selec statement:
SELECT
DATE_FORMAT(Date,'%d-%m-%Y') AS Date
FROM Purchase
WHERE Date BETWEEN '2019-02-01' AND '2019-06-30' ORDER BY Date asc;
But the data does not get sorted by date. How can I solve this?
If you use the same name for the column date and formatted date then the order by work for the alias column .. so is order by day, month, year as in your format ('%d-%m-%Y')
then try changing the alias name
SELECT DATE_FORMAT(Date,'%d-%m-%Y') AS My_Date
FROM Purchase
WHERE Date BETWEEN '2019-02-01' AND '2019-06-30'
ORDER BY Date asc;
or use a proper order by format
SELECT DATE_FORMAT(Date,'%d-%m-%Y')Date
FROM Purchase
WHERE Date BETWEEN '2019-02-01' AND '2019-06-30'
ORDER BY DATE_FORMAT(Date,'%Y-%m-%d') asc;
You can solve this by telling SQL to order by the Purchase.Date field instead of the formatted string date value. When you chose to order by "Date" with no table or table alias specified, SQL assumes you want the formatted result aliased as Date, not the "Date" field from your Purchase table.
SELECT DATE_FORMAT(Date,'%d-%m-%Y') AS My_Date
FROM Purchase
WHERE Date BETWEEN '2019-02-01' AND '2019-06-30'
ORDER BY Purchase.Date asc;

Mysql Query Select Statement Help Needed

I have a query of mysql where i fetch how much has the total sale gone ,
but it shows previous dates [Date] => 2014-01-22 [TotalSales] => 7 ,
It shows this way , how can i make it , so that it shows todays date and shows the sale up till now
SELECT DATE(order_time) AS Date, SUM(Quantity) AS TotalSales
FROM ss_orders,ss_ordered_carts
GROUP BY date;
Then add a where clause, comparing your order_time with today's date.
like this:
SELECT DATE(order_time) AS Date, SUM(Quantity) AS TotalSales
FROM ss_orders,ss_ordered_carts
WHERE DATE(order_time) = DATE(NOW())
group by date;

MySQL Query not selecting correct date range

Im currently trying to run a SQL query to export data between a certain date, but it runs the query fine, just not the date selection and i can't figure out what's wrong.
SELECT
title AS Order_No,
FROM_UNIXTIME(entry_date, '%d-%m-%Y') AS Date,
status AS Status,
field_id_59 AS Transaction_ID,
field_id_32 AS Customer_Name,
field_id_26 AS Sub_Total,
field_id_28 AS VAT,
field_id_31 AS Discount,
field_id_27 AS Shipping_Cost,
(field_id_26+field_id_28+field_id_27-field_id_31) AS Total
FROM
exp_channel_data AS d NATURAL JOIN
exp_channel_titles AS t
WHERE
t.channel_id = 5 AND FROM_UNIXTIME(entry_date, '%d-%m-%Y') BETWEEN '01-05-2012' AND '31-05-2012' AND status = 'Shipped'
ORDER BY
entry_date DESC
As explained in the manual, date literals should be in YYYY-MM-DD format. Also, bearing in mind the point made by #ypercube in his answer, you want:
WHERE t.channel_id = 5
AND entry_date >= UNIX_TIMESTAMP('2012-05-01')
AND entry_date < UNIX_TIMESTAMP('2012-06-01')
AND status = 'Shipped'
Besides the date format there is another issue. To effectively use any index on entry_date, you should not apply functions to that column when you use it conditions in WHERE, GROUP BY or HAVING clauses (you can use the formatting in SELECT list, if you need a different than the default format to be shown). An effective way to write that part of the query would be:
( entry_date >= '2012-05-01'
AND entry_date < '2012-06-01'
)
It works with DATE, DATETIME and TIMESTAMP columns.