MySQL combine 2 different counts in one query - mysql

I have a table, that pretty much looks like this:
users (id INT, masterId INT, date DATETIME)
Every user has exactly one master. But masters can have n users.
Now I want to find out how many users each master has. I'm doing that this way:
SELECT `masterId`, COUNT(`id`) AS `total` FROM `users` GROUP BY `masterId` ORDER BY `total` DESC
But now I also want to know how many new users a master has since the last 14 days. I could do it with this query:
SELECT `masterId`, COUNT(`id`) AS `last14days` FROM `users` WHERE `date` > DATE_SUB(NOW(), INTERVAL 14 DAY) GROUP BY `masterId` ORDER BY `total` DESC
Now the question: Could I somehow get this information with one query, instead of using 2 queries?

You can use conditional aggregation to do this by only counting rows for with the condition is true. In standard SQL this would be done using a case expression inside the aggregate function:
SELECT
masterId,
COUNT(id) AS total,
SUM(CASE WHEN date > DATE_SUB(NOW(), INTERVAL 14 DAY) THEN 1 ELSE 0 END) AS last14days
FROM users
GROUP BY masterId
ORDER BY total DESC
Sample SQL Fiddle

Related

MySQL: Multiple SELECT Statements in one Query

Im still learning MySQL however I would like to know how to query multiple SELECT statements in one query.
Currently I have two queries, one that displays Order count for 12 months and another for one month. I would like to query both at the same time however receive two different results.
I have tried using UNION with my query however it only outputs into one table and its quite hard to differentiate the result with what query.
SQL:
SELECT OrderDate, OrderItems, COUNT(*) AS Total FROM tb_orders WHERE OrderDate > DATE_SUB(now(), INTERVAL 12 MONTH) GROUP BY OrderItems ORDER BY Total DESC LIMIT 10
SELECT OrderDate, OrderItems, COUNT(*) AS Total FROM tb_orders WHERE OrderDate > DATE_SUB(now(), INTERVAL 1 MONTH) GROUP BY OrderItems ORDER BY Total DESC LIMIT 10;
TIA
You can merge the 2 queries by creating an identifier on the fly whether the record is from the monthly or yearly query. Column type is a column for this purpose in below query,
SELECT z.*
FROM
(
SELECT OrderDate, OrderItems, COUNT(*) AS Total, 'YEAR' as type
FROM tb_orders
WHERE OrderDate > DATE_SUB(now(), INTERVAL 12 MONTH)
GROUP BY OrderItems
LIMIT 10
UNION
SELECT OrderDate, OrderItems, COUNT(*) AS Total, 'MONTH' as type
FROM tb_orders
WHERE OrderDate > DATE_SUB(now(), INTERVAL 1 MONTH)
GROUP BY OrderItems
LIMIT 10
) AS z
ORDER BY z.Total DESC;
Working Fiddle
With union, you can always add hard-coded values to help differentiate rows:
select 'Invertebrate' as AnimalPhylum, species as AnimalSpecies from invertebrates_table
union
select 'Vertebrate', species from vertebrates_table;

Rewrite sql query to pad empty month rows

I have this query i use to get statistics of blogs in our own tracking system.
I use union select over 2 tables as we daily aggregate data in 1 table and keeps todays data in another table.
I want to have the last 10 months of traffic show.. This query does that, but of there is no traffic in a specific month that row is not in the result.
I have previously used a calendar table in mysql to join against to at avoid that, but im simply not skilled enoght to rewrite this query to join against that calendar table.
The calendart table has 1 field called "datefield" which i date format YYY-MM-DD
This is the current query i use
SELECT FORMAT(SUM(`count`),0) as `count`, DATE(`date`) as `date`
FROM
(
SELECT count(distinct(uniq_id)) as `count`, `timestamp` as `date`
FROM tracking
WHERE `timestamp` > now() - INTERVAL 1 DAY AND target_bid = 92
group by `datestamp`
UNION ALL
select sum(`count`),`datestamp` as `date`
from aggregate_visits
where `datestamp` > now() - interval 10 month
and target_bid = 92
group by `datestamp`
) a
GROUP BY MONTH(date)
Something like this?
select sum(COALESCE(t.`count`,0)),s.date as `date`
from DateTable s
LEFT JOIN (SELECT * FROM aggregate_visits
where `datestamp` > now() - interval 10 month
and target_bid = 92) t
ON(s.date = t.datestamp)
group by s.date

match timestamp with date in MYSQL using PHP

I have a table
id user Visitor timestamp
13 username abc 2014-01-16 15:01:44
I have to 'Count' total visitors for a 'User' for last seven days group by date(not timestamp)
SELECT count(*) from tableA WHERE user=username GROUPBY __How to do it__ LIMIT for last seven day from today.
If any day no visitor came so, no row would be there so it should show 0.
What would be correct QUERY?
There is no need to GROUP BY resultset, you need to count visits for a week (with unspecified user). Try this:
SELECT
COUNT(*)
FROM
`table`
WHERE
`timestamp` >= (NOW() - INTERVAL 7 DAY);
If you need to track visits for a specified user, then try this:
SELECT
DATE(`timestamp`) as `date`,
COUNT(*) as `count`
FROM
`table`
WHERE
(`timestamp` >= (NOW() - INTERVAL 7 DAY))
AND
(`user` = 'username')
GROUP BY
`date`;
MySQL DATE() function reference.
Try this:
SELECT DATE(a.timestamp), COUNT(*)
FROM tableA a
WHERE a.user='username' AND DATEDIFF(NOW(), DATE(a.timestamp)) <= 7
GROUP BY DATE(a.timestamp);
i think it's work :)
SELECT Count(*)
from table A
WHERE user = username AND DATEDIFF(NOW(),timestamp)<=7

SQL Distinct Count from a certain date range?

Have set up a query for my table where I would like to display certain reactions left within the previous weeks period, this works well when I write
SELECT *
FROM reactiondata
WHERE reaction_time > DATE_SUB(NOW(), INTERVAL 1 WEEK)
ORDER BY reaction_time ASC;
And also this query selects the unique promo ID fields and distinct usernames so you can see how many unique usernames have been sent which promo ID.
SELECT
reaction_promoID,
COUNT( DISTINCT reaction_username) AS reaction_username
FROM reactiondata GROUP BY reaction_promoID
However, I would like it so the second query works within a date range for the last week, like the first one does. When I add Where etc... to the query it does not work.
Any help hugely appeciated!
A+TS
SELECT reaction_promoID, COUNT( DISTINCT reaction_username) AS reaction_username
FROM reactiondata
WHERE reaction_time > DATE_SUB(NOW(), INTERVAL 1 WEEK)
GROUP BY reaction_promoID
I think this is time for HAVING clause:
http://www.w3schools.com/sql/sql_having.asp
SELECT reaction_promoID, COUNT( DISTINCT reaction_username) AS reaction_username
FROM reactiondata
GROUP BY reaction_promoID
HAVING reaction_time > DATE_SUB(NOW(), INTERVAL 1 WEEK)

Return a zero for a day with no results

I have a query which returns the total of users who registered for each day. Problem is if a day had no one register it doesn't return any value, it just skips it. I would rather it returned zero
this is my query so far
SELECT count(*) total FROM users WHERE created_at < NOW() AND created_at >
DATE_SUB(NOW(), INTERVAL 7 DAY) AND owner_id = ? GROUP BY DAY(created_at)
ORDER BY created_at DESC
Edit
i grouped the data so i would get a count for each day- As for the date range, i wanted the total users registered for the previous seven days
A variation on the theme "build your on 7 day calendar inline":
SELECT D, count(created_at) AS total FROM
(SELECT DATE_SUB(NOW(), INTERVAL D DAY) AS D
FROM
(SELECT 0 as D
UNION SELECT 1
UNION SELECT 2
UNION SELECT 3
UNION SELECT 4
UNION SELECT 5
UNION SELECT 6
) AS D
) AS D
LEFT JOIN users ON date(created_at) = date(D)
WHERE owner_id = ? or owner_id is null
GROUP BY D
ORDER BY D DESC
I don't have your table structure at hand, so that would need adjustment probably. In the same order of idea, you will see I use NOW() as a reference date. But that's easily adjustable. Anyway that's the spirit...
See for a live demo http://sqlfiddle.com/#!2/ab5cf/11
If you had a table that held all of your days you could do a left join from there to your users table.
SELECT SUM(CASE WHEN U.Id IS NOT NULL THEN 1 ELSE 0 END)
FROM DimDate D
LEFT JOIN Users U ON CONVERT(DATE,U.Created_at) = D.DateValue
WHERE YourCriteria
GROUP BY YourGroupBy
The tricky bit is that you group by the date field in your data, which might have 'holes' in it, and thus miss records for that date.
A way to solve it is by filling a table with all dates for the past 10 and next 100 years or so, and to (outer)join that to your data. Then you will have one record for each day (or week or whatever) for sure.
I had to do this only for MS SqlServer, so how to fill a date table (or perhaps you can do it dynamically) is for someone else to answer.
A bit long winded, but I think this will work...
SELECT count(users.created_at) total FROM
(SELECT DATE_SUB(CURDATE(),INTERVAL 6 DAY) as cdate UNION ALL
SELECT DATE_SUB(CURDATE(),INTERVAL 5 DAY) UNION ALL
SELECT DATE_SUB(CURDATE(),INTERVAL 4 DAY) UNION ALL
SELECT DATE_SUB(CURDATE(),INTERVAL 3 DAY) UNION ALL
SELECT DATE_SUB(CURDATE(),INTERVAL 2 DAY) UNION ALL
SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY) UNION ALL
SELECT CURDATE()) t1 left join users
ON date(created_at)=t1.cdate
WHERE owner_id = ? or owner_id is null
GROUP BY t1.cdate
ORDER BY t1.cdate DESC
It differs from your query slightly in that it works on dates rather than date times which your query is doing. From your description I have assumed you mean to use whole days and therefore have used dates.