SQL: Get Sum of Column AND Last Entry - mysql

I have two tables that I am joining together:
SELECT
type,
name,
SUM(value) as total_value,
target,
target_month,
operator,
SUM(value_1) as total_value1,
AVG(average_of_total) as average
FROM
(SELECT
stats.`type`, stat_type.`target`, stat_type.`target_month`, stat_type.`operator`, stats.`monthly`, stats.`value`, stats.`value_1`, stats.`created_at`, `name`, stats.`average_of_total`
FROM
tefl_stats_customer as stats
JOIN
tefl_stats_customer_type as stat_type
ON
stats.`type` = stat_type.`id`) AS all_data
WHERE
created_at BETWEEN '20147-05-09 00:00:00' AND '2017-05-10 23:00:00' AND monthly = 0
GROUP BY `type`
at the moment this is returning:
| type | Name | total_value | target | target_month | operator | total_value1 | average |
| 12 | English | 3,378 | 400 | 8000 | <= | 0 | 0 |
| 9 | Chinese | 314 | 24 | 0 | = | 426 | 2.03698 |
| 1 | Japanese | 374 | 5 | 0 | < | 78 | 6.5 |
At the moment, as you can see I am getting the SUM() of 'value' as total_value.
Value is found in the table: tefl_stats_customer. This table has thousand of rows.
How can I get the last row in the above query and to have that outputted as last_entry?

Related

How to sum values of two tables and group by date

I am building a trading system where users need to know their running account balance by date for a specific user (uid) including how much they made from trading (results table) and how much they deposited or withdrew from their accounts (adjustments table).
Here is the sqlfiddle and tables: http://sqlfiddle.com/#!9/6bc9e4/1
Adjustments table:
+-------+-----+-----+--------+------------+
| adjid | aid | uid | amount | date |
+-------+-----+-----+--------+------------+
| 1 | 1 | 1 | 20 | 2019-08-18 |
| 2 | 1 | 1 | 50 | 2019-08-21 |
| 3 | 1 | 1 | 40 | 2019-08-21 |
| 4 | 1 | 1 | 10 | 2019-08-19 |
+-------+-----+-----+--------+------------+
Results table:
+-----+-----+-----+--------+-------+------------+
| tid | uid | aid | amount | taxes | date |
+-----+-----+-----+--------+-------+------------+
| 1 | 1 | 1 | 100 | 3 | 2019-08-19 |
| 2 | 1 | 1 | -50 | 1 | 2019-08-20 |
| 3 | 1 | 1 | 100 | 2 | 2019-08-21 |
| 4 | 1 | 1 | 100 | 2 | 2019-08-21 |
+-----+-----+-----+--------+-------+------------+
How do I get the below results for uid (1)
+--------------+------------+------------------+----------------+------------+
| ResultsTotal | TaxesTotal | AdjustmentsTotal | RunningBalance | Date |
+--------------+------------+------------------+----------------+------------+
| - | - | 20 | 20 | 2019-08-18 |
| 100 | 3 | 10 | 133 | 2019-08-19 |
| -50 | 1 | - | 84 | 2019-08-20 |
| 200 | 4 | 90 | 378 | 2019-08-21 |
+--------------+------------+------------------+----------------+------------+
Where RunningBalance is the current account balance for the particular user (uid).
Based on #Gabriel's answer, I came up with something like, but it gives me empty balance and duplicate records
SELECT SUM(ResultsTotal), SUM(TaxesTotal), SUM(AdjustmentsTotal), #runningtotal:= #runningtotal+SUM(ResultsTotal)+SUM(TaxesTotal)+SUM(AdjustmentsTotal) as Balance, date
FROM (
SELECT 0 AS ResultsTotal, 0 AS TaxesTotal, adjustments.amount AS AdjustmentsTotal, adjustments.date
FROM adjustments LEFT JOIN results ON (results.uid=adjustments.uid) WHERE adjustments.uid='1'
UNION ALL
SELECT results.amount AS ResultsTotal, taxes AS TaxesTotal, 0 as AdjustmentsTotal, results.date
FROM results LEFT JOIN adjustments ON (results.uid=adjustments.uid) WHERE results.uid='1'
) unionTable
GROUP BY DATE ORDER BY date
For what you are asking you would want to union then group the results from both tables, this should give the results you want. However, I recommend calculating the running balance outside of MySQL since this adds some complexity to our query.
Weird things could start to happen, for example, if someone already defined the #runningBalance variable as part of the queries scope.
SELECT aggregateTable.*, #runningBalance := ifNULL(#runningBalance, 0) + TOTAL
FROM (
SELECT SUM(ResultsTotal), SUM(TaxesTotal), SUM(AdjustmentsTotal)
, SUM(ResultsTotal) + SUM(TaxesTotal) + SUM(AdjustmentsTotal) as TOTAL
, date
FROM (
SELECT 0 AS ResultsTotal, 0 AS TaxesTotal, amount AS AdjustmentsTotal, date
FROM adjustments
UNION ALL
SELECT amount AS ResultsTotal, taxes AS TaxesTotal, 0 as AdjustmentsTotal, date
FROM results
) unionTable
GROUP BY date
) aggregateTable

How to SUM values for DISTINCT values of another column and GROUP BY date?

How can we SUM amount for each activity only on same date and output a row for each date? This query is not working.
SELECT SUM(amount), type, date FROM table GROUP BY DISTINCT date;
Table
+----+------------+-----------+---------+
| id | date | activity | amount |
+----+------------+-----------+---------+
| 1 | 2017-12-21 | Shopping | 200 |
| 2 | 2017-12-21 | Gift | 240 |
| 3 | 2017-12-23 | Give Away | 40 |
| 4 | 2017-12-24 | Shopping | 150 |
| 5 | 2017-12-25 | Give Away | 120 |
| 6 | 2017-12-25 | Shopping | 50 |
| 7 | 2017-12-25 | Shopping | 500 |
+----+------------+-----------+---------+
Required Result
+------------+-----------+------+-----------+
| date | Shopping | Gift | Give Away |
+------------+-----------+------+-----------+
| 2017-12-21 | 200 | 240 | |
| 2017-12-23 | | | 40 |
| 2017-12-24 | 150 | | |
| 2017-12-25 | 550 | | 120 |
+------------+-----------+------+-----------+
Use:
select `date`,
sum(if (activity='Shopping', amount, null)) as 'Shopping',
sum(if (activity='Gift', amount, null)) as 'Gift',
sum(if (activity='Give Away', amount, null)) as 'Give Away'
from table
group by `date`
You can try this. It returns exact result that you want
SELECT t.date,
SUM(t.shopping_amount) AS shopping,
SUM(t.gift_amount) AS gift,
SUM(t.give_away_amount) AS give_away
FROM
(
SELECT p.`date`, p.`activity`, p.`amount` AS shopping_amount,
0 AS gift_amount, 0 AS give_away_amount
FROM products p
WHERE p.`activity` = 'Shopping'
UNION
SELECT p.`date`, p.`activity`, 0 AS shopping_amount,
p.amount AS gift_amount, 0 AS give_away_amount
FROM products p
WHERE p.`activity` = 'Gift'
UNION
SELECT p.`date`, p.`activity`, 0 AS shopping_amount,
0 AS gift_amount, p.amount AS give_away_amount
FROM products p
WHERE p.`activity` = 'Give Away'
) t
GROUP BY t.date
Hmmm, you can't pivot your results into column headers unless you know all possible values as demonstrated by slaasko but you can get the results using sql into a form which can be pivoted using your display tool ( e.g. slice of BI tool).
SELECT SUM(amount), activity, date FROM table GROUP BY date, activity;

Following SQL query returns resultset for only available months, how to get all month if data is not present?

Following query gives result-set for available months only , how can i get for all the months if data is not present .
Eg:-
Apr-2013 and May-2013 having the value but June-2013 no value how can i get June-2013 in result set as total is 0 .
SELECT CONCAT(substr(MonthName(fileddate) , 1, 3) , "-", Year(fileddate)) AS MONTH,
count(*)
FROM carstore
WHERE store=20
AND (soldstate = 2
OR soldstate = 3)
AND cartype LIKE '%Toyoto%'
AND fileddate BETWEEN DATE('2013-04-07') AND DATE('2014-04-30')
GROUP BY MONTH
ORDER BY Year(fileddate),
MONTH(fileddate) ;
+----------+----------+
| Month | count(*) |
+----------+----------+
| Apr-2013 | 2 |
| May-2013 | 2 |
| Jul-2013 | 14 |
| Aug-2013 | 3 |
| Sep-2013 | 2 |
| Nov-2013 | 4 |
| Dec-2013 | 19 |
| Jan-2014 | 61 |
| Feb-2014 | 21 |
| Apr-2014 | 3 |
+----------+----------+

Complex SQL query suggestions please

I have three tables with schema as below:
Table: Apps
| ID (bigint) | USERID (Bigint)| START_TIME (datetime) |
-------------------------------------------------------------
| 1 | 13 | 2013-05-03 04:42:55 |
| 2 | 13 | 2013-05-12 06:22:45 |
| 3 | 13 | 2013-06-12 08:44:24 |
| 4 | 13 | 2013-06-24 04:20:56 |
| 5 | 13 | 2013-06-26 08:20:26 |
| 6 | 13 | 2013-09-12 05:48:27 |
Table: Hosts
| ID (bigint) | APPID (Bigint)| DEVICE_ID (Bigint) |
-------------------------------------------------------------
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 1 | 1 |
| 4 | 3 | 3 |
| 5 | 1 | 4 |
| 6 | 2 | 3 |
Table: Usage
| ID (bigint) | APPID (Bigint)| HOSTID (Bigint) | Factor (varchar) |
-------------------------------------------------------------------------------------
| 1 | 1 | 1 | Low |
| 2 | 1 | 3 | High |
| 3 | 2 | 2 | Low |
| 4 | 3 | 4 | Medium |
| 5 | 1 | 5 | Low |
| 6 | 2 | 2 | Medium |
Now if put is userid, i want to get the count of rows of table rows for each month (of all app) for each "Factor" month wise for the last 6 months.
If a DEVICE_ID appears more than once in a month (based on START_TIME, based on joining Apps and Hosts), only the latest rows of Usage (based on combination of Apps, Hosts and Usage) be considered for calculating count.
Example output of the query for the above example should be: (for input user id=13)
| MONTH | USAGE_COUNT | FACTOR |
-------------------------------------------------------------
| 5 | 0 | High |
| 6 | 0 | High |
| 7 | 0 | High |
| 8 | 0 | High |
| 9 | 0 | High |
| 10 | 0 | High |
| 5 | 2 | Low |
| 6 | 0 | Low |
| 7 | 0 | Low |
| 8 | 0 | Low |
| 9 | 0 | Low |
| 10 | 0 | Low |
| 5 | 1 | Medium |
| 6 | 1 | Medium |
| 7 | 0 | Medium |
| 8 | 0 | Medium |
| 9 | 0 | Medium |
| 10 | 0 | Medium |
How is this calculated?
For Month May 2013 (05-2013), there are two Apps from table Apps
In table Hosts , these apps are associated with device_id's 1,1,1,4,3
For this month (05-2013) for device_id=1, the latest value of start_time is: 2013-05-12 06:22:45 (from tables hosts,apps), so in table Usage, look for combination of appid=2&hostid=2 for which there are two rows one with factor Low and other Medium,
For this month (05-2013) for device_id=4, by following same procedure we get one entry i.e 0 Low
Similarly all the values are calculated.
To get the last 6 months via query i'm trying to get it with the following:
SELECT MONTH(DATE_ADD(NOW(), INTERVAL aInt MONTH)) AS aMonth
FROM
(
SELECT 0 AS aInt UNION SELECT -1 UNION SELECT -2 UNION SELECT -3 UNION SELECT -4 UNION SELECT -5
)
Please check sqlfiddle: http://sqlfiddle.com/#!2/55fc2
Because the calculation you're doing involves the same join multiple times, I started by creating a view.
CREATE VIEW `app_host_usage`
AS
SELECT a.id "appid", h.id "hostid", u.id "usageid",
a.userid, a.start_time, h.device_id, u.factor
FROM apps a
LEFT OUTER JOIN hosts h ON h.appid = a.id
LEFT OUTER JOIN `usage` u ON u.appid = a.id AND u.hostid = h.id
WHERE a.start_time > DATE_ADD(NOW(), INTERVAL -7 MONTH)
The WHERE condition is there because I made the assumption that you don't want July 2005 and July 2006 to be grouped together in the same count.
With that view in place, the query becomes
SELECT months.Month, COUNT(DISTINCT device_id), factors.factor
FROM
(
-- Get the last six months
SELECT (MONTH(NOW()) + aInt + 11) % 12 + 1 "Month" FROM
(SELECT 0 AS aInt UNION SELECT -1 UNION SELECT -2 UNION SELECT -3 UNION SELECT -4 UNION SELECT -5) LastSix
) months
JOIN
(
-- Get all known factors
SELECT DISTINCT factor FROM `usage`
) factors
LEFT OUTER JOIN
(
-- Get factors for each device...
SELECT
MONTH(start_time) "Month",
device_id,
factor
FROM app_host_usage a
WHERE userid=13
AND start_time IN (
-- ...where the corresponding usage row is connected
-- to an app row with the highest start time of the
-- month for that device.
SELECT MAX(start_time)
FROM app_host_usage a2
WHERE a2.device_id = a.device_id
GROUP BY MONTH(start_time)
)
GROUP BY MONTH(start_time), device_id, factor
) usageids ON usageids.Month = months.Month
AND usageids.factor = factors.factor
GROUP BY factors.factor, months.Month
ORDER BY factors.factor, months.Month
which is insanely complicated, but I've tried to comment explaining what each part does. See this sqlfiddle: http://sqlfiddle.com/#!2/5c871/1/0

MySQL Return Count for All Dates in Month, Including Those w/ Zero Results

I have a MySQL table that looks like this:
+--------+------------+------------------+
| id | account_id | posted_at |
+--------+------------+------------------+
| 1 | 1 | 2013-10-05 23:09 |
| 2 | 1 | 2013-10-07 14:24 |
| 3 | 1 | 2013-10-07 01:17 |
| 4 | 1 | 2013-10-09 06:58 |
+--------+------------+------------------+
For a particular account_id (in this case 1), I want to return this (for dates in the current month):
+--------+------------+
| count | date |
+--------+------------+
| 0 | 2013-10-01 |
| 0 | 2013-10-02 |
| 0 | 2013-10-03 |
| 0 | 2013-10-04 |
| 1 | 2013-10-05 |
| 0 | 2013-10-06 |
| 2 | 2013-10-07 |
| 0 | 2013-10-08 |
| 1 | 2013-10-09 |
+--------+------------+
I have a SQL query that returns the COUNTS for each date within this month.
SELECT
DATE(posted_at) AS formatted_date,
COUNT(id) AS count
FROM entries
WHERE account_id = 1
AND MONTH(DATE(posted_at)) = MONTH(NOW())
GROUP BY formatted_date
ORDER BY formatted_date ASC
It's just returning this:
+--------+------------+
| count | date |
+--------+------------+
| 1 | 2013-10-05 |
| 2 | 2013-10-07 |
| 1 | 2013-10-09 |
+--------+------------+
Of course, COUNT doesn't return anything for dates that have no data. I want the result to have a zero for dates with no data.
I've read that you should create a join table of all possible dates. Is this the only way?
You can try something like this
Declare #INT DATETIME = null
SELECT COUNT( CASE WHEN #INT IS NOT NULL THEN #INT ELSE NULL END)
Im not to sure about mysql but in sql server it would be something like this...
SELECT
DATE(posted_at) AS formatted_date,
COUNT( CASE WHEN IS NOT NULL THEN posted_at ELSE NULL END ) AS [count]
FROM entries
WHERE account_id = 1
AND MONTH(DATE(posted_at)) = MONTH(NOW())
GROUP BY formatted_date
ORDER BY formatted_date ASC