Combine 2 MySQL queries - mysql

I have this query
SELECT COUNT(*) from `login_log` where from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
and the same one with 1 diff. it's not 1 WEEK , but 1 MONTH
how can I combine those two and assign them to aliases?

I would do this with conditional aggregation:
SELECT SUM(from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK)),
SUM(from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 MONTH))
FROM `login_log`;
MySQL treats boolean values as integers, with 1 being "true" and 0 being "false". So, using sum() you can count the number of matching values. (In other databases, you would do something similar using case.)

Use the where condition with one month internal and add the same where condition with one week internal as a Boolean column return.
I mean
Select count (*) all_in_month, (from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK)) as in_week from `login_log` where from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 a MONTH) GROUP BY in_week;
P.s. haven't tested but afaik it should work

Even though it's pretty tough to understand what you ask:
If you want them in the same column use OR
SELECT COUNT(*) from 'login_log' where from_unixtime('date') >= DATE_SUB(NOW(), INTERVAL 1 WEEK) OR from_unixtime('date') >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ;
If you don't want duplicate answers: use GROUP BY

Related

Counting all rows in column with two different date conditions

I'm trying to turn two count queries with date conditions (the ones below) into one query.
SELECT COUNT(*) as yesterday FROM orders WHERE DATE(timedate) = DATE(NOW() - INTERVAL 1 DAY)
SELECT COUNT(*) as yesterday FROM orders WHERE DATE(timedate) = DATE(NOW() - INTERVAL 2 DAY)
Following the advice of another answer I created the following, but that doesn't seem to work syntax-wise, and I'm not quite sure why. Is there another way to do this? I can't find a similar question on this
SELECT
SUM(IF(DATE(timedate) = DATE(NOW() - INTERVAL 1 DAY))) AS testcount1,
SUM(IF(DATE(timedate) = DATE(NOW() - INTERVAL 2 DAY))) AS testcount2
FROM
orders
You're missing the output values for the IF expression. Also you should use CURRENT_DATE() so you don't need to convert to a DATE:
SELECT
SUM(IF(DATE(timedate) = CURRENT_DATE() - INTERVAL 1 DAY, 1, 0)) AS testcount1,
SUM(IF(DATE(timedate) = CURRENT_DATE() - INTERVAL 2 DAY, 1, 0)) AS testcount2
FROM
orders
Note that MySQL treats boolean expressions as 1 (true) or 0 (false) in a numeric context, so you can actually SUM the expression without needing the IF:
SELECT
SUM(DATE(timedate) = CURRENT_DATE() - INTERVAL 1 DAY) AS testcount1,
SUM(DATE(timedate) = CURRENT_DATE() - INTERVAL 2 DAY) AS testcount2
FROM
orders
You want conditional aggregation. I would phrase the query as follows:
SELECT
SUM(
timedate >= CURRENT_DATE - INTERVAL 1 DAY
and timedate < CURRENT_DATE
) AS testcount1,
SUM(
timedate >= CURRENT_DATE - INTERVAL 2 DAY
and timedate < CURRENT_DATE- INTERVAL 1 DAT
) AS testcount2
FROM orders
Details:
this uses a nice feature of MySQL, that evaluates false/true conditions as 0/1 in numeric context
no date functions are applied on the timedate column : instead, we do litteral date comparisons. This is much more efficient, since the database can possibly take advantage of an index on the datetime column
You might also want to add a WHERE clause to the query:
WHERE
timedate >= CURRENT_DATE - INTERVAL 2 day
AND timedate< CURRENT_DATE

Combine two SQL queries which use Date Intervals, Group and SUM

First off, thank you in advance.
I have 2 queries that I am working with as I would like to compare last week to the previous week...
Getting Last Week
SELECT keyword,
SUM(users_desktop) AS desktop_last_week
FROM js
WHERE country='US'
AND day >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND day < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
GROUP BY keyword
ORDER BY desktop_last_week DESC
LIMIT 10;
Getting Previous Week
SELECT keyword,
SUM(users_desktop) AS desktop_previous_week
FROM js
WHERE country='US'
AND day >= curdate() - INTERVAL DAYOFWEEK(curdate())+12 DAY
AND day < curdate() - INTERVAL DAYOFWEEK(curdate())-7 DAY
GROUP BY keyword
ORDER BY desktop_previous_week DESC
LIMIT 10;
What I would like to do is combine these queries so that I can then ORDER BY the division of desktop_last_week/desktop_this_week to find keywords that are trending up (ie: searched a lot more this week than last week)
Any idea on how to combine these together?
This is called conditional aggregation. Use where clauses from your existing queries to do it.
SELECT keyword,
Sum(CASE
WHEN day >= Curdate() - INTERVAL Dayofweek(Curdate())+6 day
AND day < Curdate() - INTERVAL Dayofweek(Curdate())-1 day THEN
users_desktop
ELSE 0
end) AS desktop_last_week,
Sum(CASE
WHEN day >= Curdate() - INTERVAL Dayofweek(Curdate())+12 day
AND day < Curdate() - INTERVAL Dayofweek(Curdate())-7 day THEN
users_desktop
ELSE 0
end) AS desktop_prev_last_week
FROM js
WHERE country = 'US'
GROUP BY keyword
ORDER BY desktop_prev_last_week / desktop_this_week DESC
LIMIT 10
Use Union!
You can get 2 Queries to one with that. If you want to order that then put it into a subquery
You could expand the where clause to contain both time ranges and move the logic of differentiating between them to case expressions inside the sums. By the way, using the between operator instead of a >= and < pair would make the query itself a tad easier to read:
SELECT keyword,
SUM(CASE WHEN day BETWEEN
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) + 6 DAY) AND
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) - 1 DAY)
THEN users_desktop
END) AS desktop_last_week,
SUM(CASE WHEN day BETWEEN
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) + 12 DAY) AND
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) - 7 DAY)
THEN users_desktop
END) AS desktop_previous_week
FROM js
WHERE country = 'US'
GROUP BY keyword
ORDER BY desktop_last_week DESC, desktop_previous_week DESC
LIMIT 10;

How to get data prior to one month of what user enters in SQL

current query
SELECT col1 FROM table1 where
id=1234 and (date(sys_time)
between "2015-07-01" AND "2015-07-10")
;
I want to get the data prior to one month from the dates mentioned
here. Is there any SQL query to do it?
Just use date_sub():
SELECT col1
FROM table1
WHERE id = 1234 AND
sys_time >= date_sub('2015-07-01', interval 1 month) and
sys_time < date_add(date_sub('2015-07-01', interval 1 month), interval 1 day)
Notice that I removed the date() function from sys_time. This helps MySQL use an index for the expression, if one is available:
Try this
SELECT GETDATE() AS CurrentDate, DATEADD(dd,-30,getdate())
You could set the "current date" and the previous date as parameters and include those in your query as the critera
Use DATE_ADD("2015-07-03", INTERVAL 1 MONTH) for the adding interval
Example :
SELECT a,b FROM table WHERE from_date between DATE_ADD("2015-07-01", INTERVAL 1 MONTH) AND DATE_ADD("2015-07-03", INTERVAL 1 MONTH)

Get number of records in table during last day and last week with single query in MySQL 5.5

I have table with timestamp in one column (MySQL 5.5). Is it possible to get number of records during last 1 day (last 86400 seconds) and number of records during last week (last 604800 seconds) in single query?
I know how to do it with 2 queries, but it would be nice to know if there is some neat solution to this.
timestamp > DATE_SUB(NOW(), INTERVAL 1 DAY)
timestamp > DATE_SUB(NOW(), INTERVAL 1 WEEK)
Quick and Dirty is just a Union then.
Select '1 Days', Count(*) as NumberOf from sometable
Where `timestamp` > DATE_SUB(NOW(), INTERVAL 1 DAY)
union
Select '7 Days', Count(*) as from sometable
Where `timestamp` > DATE_SUB(NOW(), INTERVAL 1 WEEK)
Gets painful and perhaps expensive if you have a lot of ranges though. f So you might want to look at DateDiff to calculate the interval once and then count that.

How to add date condition to my query?

I have this SQL statement. It works, and I need to add another one condition.
I need to sort it by date. occurence - is my date row.
SELECT dd.caption, COUNT(t.occurence)
FROM transaction t
INNER JOIN dict_departments dd
ON dd.id = t.terminal_id
GROUP BY dd.caption
How to add this condition:
WHERE t.occurence BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH)
to my query.
Try this:
WHERE t.occurrece BETWEEN current_date() AND dateadd(month,1,current_date())
The function dateadd is a SQL SERVER function, but the rest of the clause is standard SQL.
BETWEEN requires two arguments, a start point and an end point. If your end point is the current time, you have two options:
Using BETWEEN:
WHERE t.occurence BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND NOW()
Using simple comparison operator:
WHERE t.occurence >= (CURRENT_DATE() - INTERVAL 1 MONTH)
If you want to filter dates from 1 month ago till now:
WHERE (t.occurrece BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 MONTH) AND CURDATE()) = 1
or
WHERE (t.occurrece BETWEEN ADDATE(CURDATE(), INTERVAL -1 MONTH) AND CURDATE()) = 1