mysql getting where clause weather the count is 0 or not - mysql

I wanted to show assigned_user_id in the Column User_ID whether the Meeting_Count is 0 or having value.
With below Query I'm getting only
+---------+---------------+
| User_ID | Meeting_Count |
+---------+---------------+
| NULL | 0 |
+---------+---------------+
SELECT
meeting.assigned_user_id AS User_ID,
COUNT(*) AS Meeting_Count
FROM meeting
WHERE meeting.assigned_user_id = '5c3e31bb4b708eeb5'
AND meeting.date_start >= NOW() - INTERVAL 60 DAY
My Requirement is to get as this,
+-------------------+---------------+
| User_ID | Meeting_Count |
+-------------------+---------------+
| 5c3e31bb4b708eeb5 | 0 |
+-------------------+---------------+
Can anyone help me on this. I'm still a learner.

The where clause filters out rows that do not belong to the given user, resulting in an empty resultset if no row at all matches. One workaround is to move the filtering within a conditional expression. In MySQL, you would phrase this as:
select
'5c3e31bb4b708eeb5' as user_id,
sum(assigned_user_id = '5c3e31bb4b708eeb5') as meeting_count
from meeting
where date_start >= now() - interval 60 day
If there is a possibility that the table contains no rows for the last 60 days, and you still want a result in that case, then you can take on step forward and move the date filtering to the sum() as well:
select
'5c3e31bb4b708eeb5' as user_id,
sum(assigned_user_id = '5c3e31bb4b708eeb5' and date_start >= now() - interval 60 day) as meeting_count
from meeting
This is guaranteed to always return one row.
It should be noted that conditional aggregation is by nature less efficient than filtering with a where clause.

Related

Select nearest date in the interval

I'm trying to select rows in which 3+ posts is in the interval 14 days.
For example:
User | id_post | date
1 | 12 | 2018-01-01
1 | 13 | 2018-01-05
1 | 14 | 2018-01-21
1 | 15 | 2018-01-27
1 | 16 | 2018-01-29
2 | 17 | 2018-01-01
2 | 18 | 2018-01-20
2 | 19 | 2018-02-17
2 | 20 | 2018-03-07
2 | 21 | 2018-04-29
User = OwnerUserId
date = CreationDate
In this case I need to return just User 1 because he has posts which are in 14 days.
Please, help me how I can get it. Thank you
Update: A user should have posts which were published in the interval of 14 days. It can be more, for example if the last day is in 2019 but in 2018 there was 3posts published within 14 days - it's ok
now i have (data get from data.stackexchange stackoverflow) and tried to apply
select OwnerUserId from Posts as p
where OwnerUserId in (select Users.id from Users WHERE YEAR (Users.CreationDate) >= 2017)
AND YEAR (p.CreationDate) >= 2018
AND p.Tags like '%sql%'
join (select OwnerUserId, CreationDate as startdate, dateadd(day,14,CreationDate) as enddate
from Posts) as r
on p.OwnerUserId = r.OwnerUserId and p.CreationDate between r.startdate and r.enddate
group by p.OwnerUserId, CreationDate
having count(*) >= 3
but it replies
Incorrect syntax near the keyword 'join'.
Incorrect syntax near the keyword 'as'.
I'm a begginner here and in the sql, so i dont exactly know how to combine my previous 'filtr' and current join with date
I'll not tell you the solution, but give you some pseudo-code and you figure out how to code it in SQL-
a) You should restrict your data for just 14 days.
b) Now, make groupings by User and find the count of records/lines present (for each User).
c) Now, again do a filter check to find users whose count of records is greater than 3.
Now, tell us which SQL keywords will be used for each points above.
I think something like
select p.user_id
from posts p
join (select user_id, xdate start_date, date_add(xdate, interval 14 day) end_date
from posts) r
on p.user_id = r.user_id and p.xdate between r.start_date and r.end_date
group by user_id, start_date
having count(*) >= 3
can help. It may not be the best possible solution, but it works.
Check it on SQL Fiddle
If you just want to select users by id you may try
Select id_post, date from yourtable where user = 2 order by id DESC limit 10;
You should have Colum called id with auto increment so new posts will have higher id so when it's sorted in descending it will start with post with higher id also you should have index on that id colum auto increment and index
If you don't want to use the above method then you will do that with date range like this
$date = gmdate() - (3600*24); 24 is 24 hours past
Select id_post, title from mutable where add_date > 'value of $date'
In both cases you should have index on user id
The second query is what you need but you should get the date from the equation first then apply it to the query
First, I think you mean user 1 not 2.
In MySQL 8+, this is pretty easy. If you want the first such post:
select t.*
from (select t.*,
lead(date, 2) over (partition by user order by date) as next_date2
from t
) t
where next_date2 <= date + interval 14 day;

Count unique days grouped by user

I have the following SQL table
|user|log_date |
| 2 |2016-06-23 10:55:52 |
| 2 |2016-06-23 10:55:54 |
| 2 |2016-06-24 10:53:54 |
| 2 |2016-06-24 10:54:54 |
and so on with many other users and log_dates. What I want is to check for whole month :
where left(log_date,7)="2016-06"
But I want to count one day only once per day. So the result for my table in this example should be :
|user|count of unique days|
| 2 | 2 |
and I want it to be grouped by users. So for every user in table I want to count unique days.
Can anybody give me a hint?
Writing the condition this way allows the use of an index...
SELECT t.user
, COUNT(DISTINCT DATE(t.log_date)) unique_days
FROM my_table t
WHERE t.log_date BETWEEN '2016-06-01 00:00:00' AND '2016-06-31 23:59:59' -- or t.log_date >= '2016-06-01 00:00:00' AND t.log_date < '2016-07-01 00:00:00'
GROUP
BY t.user;
(Not sure why Sagi deleted their answer after correcting it)
Try this:
select
user,
count(distinct day(log_date)) as `count of unique days`
from yourtable
where left(log_date, 7) = '2016-06'
group by user
SQLFiddle Demo

MySQL: query with condition on one-to-many table

I have a table with schema like this:
clients_actions
id | client_id | action | date_done
1 | 1 | ... | 1394785392
2 | 2 | ... | 1394786392
3 | 2 | ... | 1394787392
date_done can be set both in the past, and in the future from current unix timestamp. I need to select all 'forgotten' clients, which don't have date_done set in future (in all his actions) and last his action is older than 604800 seconds (7 days). Client can have many actions. And also, if it's possible, I need in the same query to select his last action (which is in past and more than 7 days old).
How can it be done?
One way to do it as
select * from clients_actions
where from_unixtime(date_done) < date_sub(now(),INTERVAL 7 day)
AND client_id
NOT IN
(
select client_id from
clients_actions
where from_unixtime(date_done) > now()
)
;
DEMO
In the demo I have added some data with future dates so that they can be ignored and just by getting data older than 7 days. You can do group by in case there are repeated data in your table.
Select client_id, action, MAX(date_done) from clients_actions
WHERE date_done < (UNIX_TIMESTAMP(SYSDATE() - 7)
AND id NOT IN (SELECT id FROM clients_actions
WHERE date_done > (UNIX_TIMESTAMP(SYSDATE()))
GROUP BY client_id;
For the first part you want a query that has Where date_done < SysDate - 7 days and client_id not in (select id from clients_actions where date_done > SysDate (also converted to UNIX). This says I want all records whose date_done is older than 7 days ago, but that don't have any actions due in the future.
the MAX and group by client_id limit it to only the latest record of those selected by client_id.
The following query will get you the desired result.
SELECT *
FROM clients_actions ca
INNER JOIN
(SELECT client_id, MAX(date_done) as date_done
FROM clients_actions
WHERE DATEDIFF(CURRENT_TIMESTAMP, FROM_UNIXTIME(date_done)) >= 7
GROUP BY client_id) latest_date
ON ca.client_id = latest_date.client_id AND ca.date_done = latest_date.date_done;

MySQL LEFT JOIN SUM doen not include 0

Guess there are many varianat of this question, however this has a twist.
My primary table contains logged kilometers for certain dates for certain users:
Table km_run:
|entry|mnumber|dato |km | where 'dato' is the specific date. Formats are like:
|1 |3 |2013-01-01|5.7|
For a specific user ('mnumber') I want to calculate the sum in each week of a year. For this purpose I have made a 'dummy-table' just containing the week numbers from 1 to 53:
Table `week_list`:
|week|
|1 |
|2 |
etc..
This query gives the sum, however I cannot find a way to return a zero if there are no entries in 'km_run' for the specific week.
SELECT `week_list`.`week`, WEEKOFYEAR(`km_run`.`dato`), SUM(`km_run`.`km`)
FROM `week_list` LEFT JOIN `km_run` ON WEEKOFYEAR(`dato`) = `week_list`.`week`
WHERE `km_run`.`mnumber` = 3 AND `km_run`.`dato` >= '2013-01-01'
AND `km_run`.`dato` < '2014-01-01'
GROUP BY WEEKOFYEAR(`dato`)
I have tried to do COALESCE( SUM(km),0) and I have also tried to use the IFNULL function around the sum. Despite the left join, not all records from week_list are returned in the sql statement.
Here's the result:
week | WEEKOFYEAR(`km_run`.`dato`) | SUM(`km_run`.`km`)
1 | 1 | 58.4
3 | 3 | 50.7
4 | 4 | 39.2
As you can see, week two is skipped instead of returning a 0
Firstly JOIN works, creating such rows:
week=2 weekofyear=null mnumber=null sum=0 ...
Then, WHERE clause (for example, where mnumber=3) excludes rows with nulls.
You could try something like this:
SELECT week, SUM(km) FROM (
(SELECT km_run.km AS km, WEEKOFYEAR(km_run.dato) AS week
FROM km_run
WHERE mnumber = 3 AND km_run.dato >= '2013-01-01' AND km_run.dato < '2014-01-01')
UNION
(SELECT 0 AS km, week_list.week as week FROM week_list)
) GROUP BY week

MySQL - Count Yearly Totals when some Years have nulls

I have 1 table with similar data:
CustomerID | ProjectID | DateListed | DateCompleted
123456 | 045 | 07-29-2010 | 04-03-2011
123456 | 123 | 10-12-2011 | 11-30-2011
123456 | 157 | 12-12-2011 | 02-10-2012
123456 | 258 | 06-07-2011 | NULL
Basically, a customer contacts us, we get a project on our list, and we mark it completed when we're done with it.
What I'm after is a simple (you'd think, at least) count of all projects, with expected output like below:
YEAR | TotalListed | TotalCompleted
2010 | 1 | 0
2011 | 3 | 2
2012 | 0 | 1
However, my query below - because of the join - isn't showing 2012's count, because there's been no listed project for 2012. However, I can't really reverse the query, as then 2010's count wouldn't show up (since nothing was completed in 2010).
I'm open to any suggestions, or tips like how to do this. I've pondered a temp table, is that the best way to go? I'm open to anything that gets me what I need!
(If the code looks familiar, ya'll helped me get the subquery made! MySQL Subquery with main query data variable)
SELECT YEAR(p1.DateListed) AS YearListed, COUNT(p1.ProjectID) As Listed, PreQuery.Completed
FROM(
SELECT YEAR(DateCompleted) AS YearCompleted, COUNT(ProjectID) AS Completed
FROM projects
WHERE CustomerID = 123456 AND DateListed >= DATE_SUB(Now(), INTERVAL 5 YEAR)
GROUP BY YEAR(DateCompleted)
) PreQuery
RIGHT OUTER JOIN projects p1 ON PreQuery.YearCompleted = YEAR(p1.DateListed)
WHERE CustomerID = 123456 AND DateListed >= DATE_SUB(Now(), INTERVAL 5 YEAR)
GROUP BY YearListed
ORDER BY p1.DateListed
After reviewing your table, query, and expected results - I believe I have found a more-revised query to suit your needs. It is a fairly-full rewrite of your existing query though, but I've tested it with your given data and received the same results you want/expect:
SELECT
years.`year`,
SUM(IF(YEAR(DateListed) = years.`year`, 1, 0)) AS TotalListed,
SUM(IF(YEAR(DateCompleted) = years.`year`, 1, 0)) AS TotalCompleted
FROM
projects
LEFT JOIN (
SELECT DISTINCT `year` FROM (
SELECT YEAR(DateListed) AS `year` FROM projects
UNION SELECT YEAR(DateCompleted) AS `year` FROM projects WHERE DateCompleted IS NOT NULL
) as year_inner
) AS years
ON YEAR(DateListed) = `year`
OR YEAR(DateCompleted) = `year`
WHERE
CustomerID = 123456 AND DateListed >= DATE_SUB(Now(), INTERVAL 5 YEAR)
GROUP BY
years.`year`
ORDER BY
years.`year`
To explain, we should start with the inner query (aliased as year_inner). It selects a full list of years in the DateListed and DateCompleted columns and then selects a DISTINCT list of those to create the years alias sub-query. This sub-query is used to get a full list of "years" that we want data for. Doing it this way, opposed to a sub-query with counts and groupings will allow you to only have to define the WHERE clause on the outermost query (though, if efficiency becomes an issue with thousands and thousands of records, you could always add a WHERE clause to the inner query too; or an index to the date columns).
After we've built our inner queries, we join the projects table on the results with a LEFT JOIN for the DateListed or DateCompleted's YEAR() value - which will allow us to bring back null columns too!
For the field selections, we use the year column from our inner query to assure that we get a full list of years to display. Then, we compare the current row's DateListed & DateCompleted YEAR() value to the current year; if they're equal, add 1 - else add 0. When we GROUP BY year, our SUM() will count all of the 1's for that year for each column and give you the output you want (hopefully, of course =P).