SUM DISTINCT MYSQL | WHERE CLAUSE - mysql

I would like to get results based on SUM from table (history), where username contains 'red' and grouped by month. here the query :
select month(date),
SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) as total_sucess,
SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as total_failed
from history
where date between '201305%' AND '201311%' AND username like '%#red%'
GROUP BY month(history.date);
the results :
+------------+--------------+--------------+
| month(date) | total_sucess | total_failed |
+------------+--------------+--------------+
| 5 | 10960 | 3573 |
| 6 | 2336 | 1202 |
| 7 | 2211 | 1830 |
| 8 | 5312 | 3125 |
| 9 | 9844 | 5407 |
| 10 | 6351 | 3972 |
+------------+--------------+--------------+
the question is , how do I get distinct total_success and total_failed SUM? just in one query ?
I've tried using this
select month(tgl),
SUM(CASE WHEN status='success' THEN 1 ELSE 0 END) as total_sucess,
SUM(DISTINCT (username) CASE WHEN status='success' THEN 1 ELSE 0 END) as distinct_total_sucess,
SUM(CASE WHEN status='failed' THEN 1 ELSE 0 END) as total_failed,
SUM(DISTINCT (username) CASE WHEN status='failed' THEN 1 ELSE 0 END) as distinct_failed_sucess
from history_auth
where tgl between '201305%' AND '201311%' AND username like '%#t.sel%'
GROUP BY month(history_auth.tgl);
but get error sql syntax... i have no idea with this :(

Best I can make out of your requirement is that you want the number of distinct usernames each month that succeeded / failed.
If so I think you need a pair of sub selects to get those figures.
Rejigged the query (adding another sub select to get the 6 months, rather than relying on all months being represented.
SELECT Sub1.aMonth,
SUM(CASE WHEN history.status='success' THEN 1 ELSE 0 END) as total_sucess,
SUM(CASE WHEN history.status='failed' THEN 1 ELSE 0 END) as total_failed,
IFNULL(SuccessCount, 0),
IFNULL(FailedCount, 0)
FROM
(
SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 0 MONTH)) AS aMonth
UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 1 MONTH))
UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 2 MONTH))
UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 3 MONTH))
UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 4 MONTH))
UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 5 MONTH))
UNION SELECT MONTH(DATE_SUB('2013-11-01', INTERVAL 6 MONTH))
) Sub1
LEFT OUTER JOIN history
ON MONTH(history.date) = Sub1.aMonth
AND username LIKE '%#red%'
LEFT OUTER JOIN
(
SELECT MONTH(date) AS aMonth, COUNT(DISTINCT username) AS SuccessCount
FROM history
WHERE status='success'
AND username LIKE '%#red%'
GROUP BY MONTH(date)
) Sub2
ON Sub1.aMonth = Sub2.aMonth
LEFT OUTER JOIN
(
SELECT MONTH(date) AS aMonth, COUNT(DISTINCT username) AS FailedCount
FROM history
WHERE status='failed'
AND username LIKE '%#red%'
GROUP BY MONTH(date)
) Sub3
ON Sub1.aMonth = Sub3.aMonth
GROUP BY Sub1.aMonth, SuccessCount, FailedCount

Related

get total amount of expenses per month in MySQL

I am currently working with 2 tables, expenses and income. To keep the structure simple and can see it, this is the fiddle: http://sqlfiddle.com/#!9/256cd64/2
The result I need from my query is the total amount for each month of the current year, for this and tried something like this:
select sum(e.amount) as expense, DATE_FORMAT(e.date,'%m') as month
from expenses e
where year(e.date) = 2019
group by month
My problem with this is that it only takes me the months where there was registration and I would like it to take 12 months whether or not they have a registration, in the case that they did not return 0 as a total amount.
At the moment I am working with the table of expenses but I would like to have a single query that returns the monthly expenses and income, this is an example of the final output that I would like to obtain:
| Month | Expense| Incomes |
|---------|--------|---------|
| 01| 0 | 0 |
| 02| 3000 | 4000 |
| 03| 1500 | 5430 |
| 04| 2430 | 2000 |
| 05| 2430 | 1000 |
| 06| 2430 | 1340 |
| 07| 0 | 5500 |
| 08| 2430 | 2000 |
| 09| 1230 | 2000 |
| 10| 8730 | 2000 |
| 11| 2430 | 2000 |
| 12| 6540 | 2000 |
You need to generate the month values and then use left join to match to expenses:
select coalesce(sum(e.amount), 0) as expense, m.month
from (select '01' as month union all
select '02' as month union all
select '03' as month union all
select '04' as month union all
select '05' as month union all
select '06' as month union all
select '07' as month union all
select '08' as month union all
select '09' as month union all
select '10' as month union all
select '11' as month union all
select '12' as month
) m left join
expenses e
on year(e.date) = 2019 and
DATE_FORMAT(e.date,'%m') = m.month
group by m.month;
Here is a db<>fiddle.
As for income, you should ask another question about that.
You can use MONTH to get month value from your date column and then GROUP BY them to get your desired output as below-
SELECT SUM(e.amount) AS expense,
MONTH(e.date) AS month
FROM expenses e
WHERE YEAR(e.date) = 2019
GROUP BY MONTH(e.date)
Try changing your sum(e.amount) as expense to: COALESCE(sum(e.amount),0) as expense
The COALESCE function returns the first non NULL value.
SELECT
t1.month,
COALESCE(t2.amount, 0) AS expenses,
COALESCE(t3.amount, 0) AS incomes
FROM
(
SELECT 1 AS month UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9 UNION ALL
SELECT 10 UNION ALL
SELECT 11 UNION ALL
SELECT 12
) t1
LEFT JOIN
(
SELECT MONTH(date) AS month, SUM(amount) AS amount
FROM expenses
GROUP BY MONTH(date)
) t2
ON t1.month = t2.month
LEFT JOIN
(
SELECT MONTH(date) AS month, SUM(amount) AS amount
FROM incomes
GROUP BY MONTH(date)
) t3
ON t1.month = t3.month
ORDER BY
t1.month;

query to find closest lesser date

I have a table with lunch effective date and its rate.
I need to display rate from its nearest lesser effective date (created_on) for each date column.
lunch_rate table:
created_on | rate
-----------+-------
2018-06-01 | 30
2018-06-04 | 60
Here's what I tried to do:
SELECT userId,
SUM(CASE WHEN date= '2018-06-01' AND lunchStatus = 1 THEN (SELECT MAX(rate) FROM lunch_rate WHERE DATE(created_on) <= date LIMIT 1) ELSE 0 END) '2018-06-01',
SUM(CASE WHEN date= '2018-06-02' AND lunchStatus = 1 THEN (SELECT MAX(rate) FROM lunch_rate WHERE DATE(created_on) <= date LIMIT 1) ELSE 0 END) '2018-06-02',
SUM(CASE WHEN date= '2018-06-03' AND lunchStatus = 1 THEN (SELECT MAX(rate) FROM lunch_rate WHERE DATE(created_on) <= date LIMIT 1) ELSE 0 END) '2018-06-03',
SUM(CASE WHEN date= '2018-06-04' AND lunchStatus = 1 THEN (SELECT MAX(rate) FROM lunch_rate WHERE DATE(created_on) <= date LIMIT 1) ELSE 0 END) '2018-06-04'
FROM
(
SELECT userId, lunchStatus, DATE(issuedDateTime) as date
FROM `lunch_status`
WHERE DATE(issuedDateTime) BETWEEN '2018-06-01' AND '2018-06-04'
) as a
GROUP BY userId;
But this query only gives maximum rate of all, without considering the nearest effective date.
Here's the outcome:
userId | 2018-06-01 | 2018-06-02 | 2018-06-03 | 2018-06-04
------------------------------------------------------------------------
131 | 60 | 60 | 0 | 60
132 | 60 | 60 | 60 | 0
133 | 0 | 0 | 0 | 60
134 | 0 | 0 | 0 | 60
Expected outcome:
userId | 2018-06-01 | 2018-06-02 | 2018-06-03 | 2018-06-04
------------------------------------------------------------------------
131 | 30 | 30 | 0 | 60
132 | 30 | 30 | 30 | 0
133 | 0 | 0 | 0 | 60
134 | 0 | 0 | 0 | 60
SUM(CASE WHEN ... THEN (SELECT MAX(rate) FROM lunch_rate WHERE DATE(created_on) <= date LIMIT 1) ELSE 0 END) ....',
How can I select lunch rate that was effective on that date?
If I understand correctly, you want the calculation in the subquery:
SELECT userId,
SUM(CASE WHEN date = '2018-06-01' AND lunchStatus = 1
THEN rate ELSE 0
END) as `2018-06-01`,
SUM(CASE WHEN date = '2018-06-02' AND lunchStatus = 1
THEN rate ELSE 0
END) as `2018-06-02`,
SUM(CASE WHEN date = '2018-06-03' AND lunchStatus = 1
THEN rate ELSE 0
END) as `2018-06-03`,
SUM(CASE WHEN date = '2018-06-04' AND lunchStatus = 1
THEN rate ELSE 0
END) as `2018-06-04`
FROM (SELECT ls.*, DATE(ls.issuedDateTime) as date
(SELECT lr.rate
FROM lunch_rate lr
WHERE DATE(lr.created_on) <= DATE(ls.issuedDateTime)
ORDER BY lr.created_on DESC
LIMIT 1
) as rate
FROM lunch_status ls
WHERE DATE(issuedDateTime) BETWEEN '2018-06-01' AND '2018-06-04'
) lr
GROUP BY lr.userId;
Note the other changes:
The subquery for lunch_rate does not use MAX(). Instead, it uses ORDER BY.
The column aliases are surrounded by backticks, not single quotes. I don't approve of the names (because they need to be escaped). But if you want them, use proper escape characters.
The tables are given reasonable aliases and column names are qualified.
You could try something like this:
SELECT lr1.rate
FROM lunch_rate lr1
WHERE lr1.created_on <= my_date
AND NOT EXISTS (SELECT *
FROM lunch_rate lr2
WHERE lr2.created_on > lr1.created_on
AND lr2.created_on <= my_date);

Set default value if no result found

I have the following query
SELECT count(*) as count, Month(created_at) as month
FROM products
WHERE marketplace_id=21
and status='counterfeit'
and created_at < Now()
and created_at > DATE_ADD(Now(), INTERVAL - 5 MONTH)
group by month(created_at)
it return result as
+-------+-------+
| count | month |
+-------+-------+
| 410 | 1 |
| 174 | 2 |
| 301 | 3 |
| 329 | 4 |
| 141 | 12 |
+-------+-------+
in case a month does not have values it doesn't returns it at all, but I want the default value 0 to be set for that month.
I have tried this link Return a default value if no rows found
and
Returning a value if no result
I am not sure whether I am not able to implement it correctly or this is not what I want
Try this, seems to be a little stupid, but may help for you;)
SELECT SUM(count) AS count, month
FROM (
SELECT count(*) as count, Month(created_at) as month FROM products WHERE marketplace_id=21
and status='counterfeit' and created_at < Now() and created_at > DATE_ADD(Now(), INTERVAL - 5 MONTH)
group by month(created_at)
UNION
SELECT * FROM (
SELECT 0 AS count, 1 AS month
UNION SELECT 0 AS count, 2 AS month
UNION SELECT 0 AS count, 3 AS month
UNION SELECT 0 AS count, 4 AS month
UNION SELECT 0 AS count, 5 AS month
UNION SELECT 0 AS count, 6 AS month
UNION SELECT 0 AS count, 7 AS month
UNION SELECT 0 AS count, 8 AS month
UNION SELECT 0 AS count, 9 AS month
UNION SELECT 0 AS count, 10 AS month
UNION SELECT 0 AS count, 11 AS month
UNION SELECT 0 AS count, 12 AS month) M
WHERE M.month < Month(Now()) AND M.month > Month(DATE_ADD(Now(), INTERVAL - 5 MONTH)))
) tmp
GROUP BY mouth
ORDER BY month
You could create another table with default values
test_defaults
-----------------
| month | count |
and than just left join it with your table of values so if the value is found within the main table, it will be used, if not value from test_defaults would be used (we will use COALESCE function which returns first non null value):
SELECT t1.month, COALESCE(t2.count, t1.count)
FROM test_defaults t1
LEFT JOIN test_data t2 ON t1.month = t2.month
ORDER BY t1.month;
Here's a working SqlFiddle demo

How can I get the number of records for today in five-minute intervals?

Assuming I have a column named creation_timestamp on a table named bank_payments, I would like to break today into five-minute intervals, and then query the database for the count in each of those intervals.
I'm going to read this manually (i.e. this is not for consumption by an application), so the output format does not matter as long as I can use it to get the five-minute time period, and the count of records in that period.
Is it possible to do this entirely on the side of the database?
If you want to group by your records in table on 5 min interval then you can try this:
SELECT col1, count(col1), creation_timestamp
FROM bank_payments
WHERE DATE(`creation_timestamp`) = CURDATE()
GROUP BY UNIX_TIMESTAMP(creation_timestamp) DIV 300, col1
Yes. Here is one method:
select sec_to_time(floor(time_to_sec(time(datetimecol)*5/60))), count(*)
from t
where t.datetimecol >= curdate() and
t.dattimeecol < curdate() + interval 1 day
group by 1
order by 1;
If you are expecting an output like
| begin_time | end_time | cnt |
|---------------------|---------------------|-----|
| 2015-12-28 | 2015-12-28 00:05:00 | 1 |
| 2015-12-28 01:00:00 | 2015-12-28 01:05:00 | 4 |
| 2015-12-28 01:05:00 | 2015-12-28 01:10:00 | 1 |
| 2015-12-28 02:55:00 | 2015-12-28 03:00:00 | 4 |
| 2015-12-28 03:05:00 | 2015-12-28 03:10:00 | 1 |
| 2015-12-28 03:10:00 | 2015-12-28 03:15:00 | 1 |
Then
select
begin_time,
end_time,
sum(case when creation_timestamp between begin_time and end_time then 1 else 0 end) cnt
from (
select #r begin_time, #r := #r + INTERVAL 5 MINUTE end_time
from (select #r := curdate()) r,
(select 1 union all select 1 union all select 1 union all select 1) a1, #4
(select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1) a2, #6 * 4 = 24
(select 1 union all select 1 union all select 1 union all select 1) a3, #4 * 24 = 96
(select 1 union all select 1 union all select 1) a4 #3 * 96 = 288
) x,
(select creation_timestamp from bank_payments) y
group by begin_time, end_time
If you only need those intervals having count > 0 then
select
begin_time,
end_time,
sum(case when creation_timestamp between begin_time and end_time then 1 else 0 end) cnt
from (
select #r begin_time, #r := #r + INTERVAL 5 MINUTE end_time
from (select #r := curdate()) r,
(select 1 union all select 1 union all select 1 union all select 1) a1, #4
(select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1) a2, #6 * 4 = 24
(select 1 union all select 1 union all select 1 union all select 1) a3, #4 * 24 = 96
(select 1 union all select 1 union all select 1) a4 #3 * 96 = 288
) x,
(select creation_timestamp from bank_payments) y
group by begin_time, end_time
having sum(case when creation_timestamp between begin_time and end_time then 1 else 0 end) > 0
sql fiddle demo

MySql Single Table, Select last 7 days and include empty rows

I have searched similar problems here on stackoverflow but I could not understand how to make this work, what I'm trying to do...
So, I want to get last 7 days transactions from database and get total sales amount and also include empty rows if there is no data for some day.
What I have so far:
http://sqlfiddle.com/#!2/f4eda/6
This outputs:
| PURCHASE_DATE | AMOUNT |
|---------------|--------|
| 2014-04-25 | 19 |
| 2014-04-24 | 38 |
| 2014-04-22 | 19 |
| 2014-04-19 | 19 |
What I want:
| PURCHASE_DATE | AMOUNT |
|---------------|--------|
| 2014-04-25 | 19 |
| 2014-04-24 | 38 |
| 2014-04-23 | 0 |
| 2014-04-22 | 19 |
| 2014-04-21 | 0 |
| 2014-04-20 | 0 |
| 2014-04-19 | 19 |
Any help appreciated :)
This is not easy. I took help from this thread generate days from date range and combined it with your query.
So the idea was to get the list of dates from last 7 days then left join these dates with a static amount 0 to the query you have and then finally sum them. This could be used for any date range, just need to change them in both the queries
select
t1.purchase_date,
coalesce(SUM(t1.amount+t2.amount), 0) AS amount
from
(
select DATE_FORMAT(a.Date,'%Y-%m-%d') as purchase_date,
'0' as amount
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
)t1
left join
(
SELECT DATE_FORMAT(purchase_date, '%Y-%m-%d') as purchase_date,
coalesce(SUM(amount), 0) AS amount
FROM transactions
WHERE purchase_date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
AND vendor_id = 0
GROUP BY purchase_date
)t2
on t2.purchase_date = t1.purchase_date
group by t1.purchase_date
order by t1.purchase_date desc
DEMO
Simply put together a subquery with the dates you want and use left outer join:
select d.thedate, coalesce(SUM(amount), 0) AS amount
from (select date('2014-04-25') as thedate union all
select date('2014-04-24') union all
select date('2014-04-23') union all
select date('2014-04-22') union all
select date('2014-04-21') union all
select date('2014-04-20') union all
select date('2014-04-19')
) d left outer join
transactions t
on t.purchase_date = d.thedate and vendor_id = 0
GROUP BY d.thedate
ORDER BY d.thedate DESC;
This is for last 7 days;
select d.thedate, coalesce(SUM(amount), 0) AS amount
from (select DATE(NOW()) as thedate union all
select DATE(DATE_SUB( NOW(), INTERVAL 1 DAY)) union all
select DATE(DATE_SUB( NOW(), INTERVAL 2 DAY)) union all
select DATE(DATE_SUB( NOW(), INTERVAL 3 DAY)) union all
select DATE(DATE_SUB( NOW(), INTERVAL 4 DAY)) union all
select DATE(DATE_SUB( NOW(), INTERVAL 5 DAY)) union all
select DATE(DATE_SUB( NOW(), INTERVAL 6 DAY))) d left outer join
transactions t
on t.purchase_date = d.thedate and vendor_id = 0
GROUP BY d.thedate
ORDER BY d.thedate DESC;
with recursive all_dates(dt) as (
select '2014-04-19' as dt
union all
select dt + interval 1 day
from all_dates
where dt + interval 1 day <= '2014-04-25'
)
select d.dt as purchase_date, coalesce(m.amount, 0) as purchased
from all_dates as d
left join mytable m
on d.dt = m.purchase_date
order by purchase_date desc;