MySql : Get data from two tables - mysql

I am stuck with mysql query.Not able to proceed.
I have 2 tables where user's login time is recorded.Login time should be considered when either of the table contains entry. I want to find userwise sum of logins for a month.
I could reach till here. But not able to understand how to get sum
select table1.employeeId
, date(table1.loginTime) as date1
, date(table2.loginTime) as date2
from table1
inner join table2 on table1.employeeId=table2.employeeId
and table1.loginTime>='2017-01-01 00:00:00'
and table1.loginTime<='2017-01-31 23:59:59'
and table2.loginTime>='2017-01-01 00:00:00'
and table2.loginTime<='2017-01-31 23:59:59'
For ex : count=0
employe1 logged
on 1-Jan-2017 in table1 & table2 <- count++ (if he logs in 2 tables then only 1 count should be considered)
on 2-Jan-2017 in table1 <- count++
So for employee1 count is 2

You could do this with outer joins, but it would be needlessly complex:
select employeeId
, count(*) as loginCount
from ( select employeeId
, loginTime
from table1
where loginTime between '2017-01-01 00:00:00'
and '2017-01-31 23:59:59'
union
select employeeId
, loginTime
from table2
where loginTime between '2017-01-01 00:00:00'
and '2017-01-31 23:59:59'
( as a
group by employeeId;

Another approach:
SELECT
employeeId,
COUNT(1)+
(
SELECT COUNT(1)
FROM TABLE2 T2
WHERE MONTH(T2.loginTime) = 1
AND YEAR(T2.loginTime) = 2017
AND T2.employeeId = T1.employeeId
)
AS LOGINTIMES
FROM
TABLE1 T1
WHERE MONTH(loginTime) = 1
AND YEAR(loginTime) = 2017
GROUP BY employeeId
Sample fiddle: http://sqlfiddle.com/#!9/45ce27/3/0

Related

Combine 2 sql queries into 1 query

I have 2 queries right now for which I am looking to combine into 1 if possible.
I have open tickets stored in the Tickets_Open table and closed tickets in Tickets_Closed. Both tables have "Date_Requested" and "Date_Completed" columns. I need to count the number of tickets requested and completed each day.
My tickets requested count query is the following:
SELECT SUM(Count) AS TotalOpen, Date FROM(
SELECT COUNT(Ticket_Request_Code) AS Count, Date_Requested AS Date
FROM Tickets_Closed
WHERE Date_Requested >='2018-01-01 00:00:00'
GROUP BY(Date_Requested)
UNION
SELECT COUNT(Work_Request_Code) AS Count, Date_Requested AS Date
FROM Tickets_Open
WHERE Date_Requested >='2018-01-01 00:00:00'
GROUP BY(Date_Requested)
) AS t1 GROUP BY Date ORDER BY `t1`.`Date` DESC
My tickets completed count query is the following:
SELECT COUNT(Ticket_Request_Code) AS CountClosed, Date_Completed AS Date
FROM Tickets_Closed
Where Date_Completed >='2018-01-01 00:00:00'
GROUP BY(Date_Completed)
Both queries return the correct result. For open it returns with the column headings Date and TotalOpen. For close it returns with the column headings Date and CountClosed.
Is it possible to return it with the following column headings Date, TotalOpen, CountClosed.
You can combine these as:
SELECT Date, SUM(isopen) as isopen, SUM(isclose) as isclose
FROM ((SELECT date_requested as date, 1 as isopen, 0 as isclose
FROM Tickets_Closed
WHERE Date_Requested >= '2018-01-01'
) UNION ALL
(SELECT date_requested, 1 as isopen, 0 as isclose
FROM Tickets_Open
WHERE Date_Requested >= '2018-01-01'
) UNION ALL
(SELECT date_closed as date, 0 as isopen, 1 as isclose
FROM Tickets_Closed
WHERE date_closed >= '2018-01-01'
)
) t
GROUP BY Date
ORDER BY Date DESC;
This assumes that Ticket_Request_Code and Work_Request_Code are not NULL. If COUNT() is really being used to check for NULL values, then add the condition to the WHERE clause in each subquery.
This query uses the FULL OUTER JOIN on the Dates as well, but it correctly adds the Open/Closed counts together to give you a TotalOpen Count. This will also handle possible NULL values for cases where you have a day that doesn't close any tickets.
WITH open AS
(
SELECT COUNT(Work_Request_Code) AS OpenCount, Date_Requested AS Date
FROM Tickets_Open
WHERE Date_Requested >='2018-01-01 00:00:00'
GROUP BY(Date_Requested)
)
, close AS
(
SELECT COUNT(Ticket_Request_Code) AS ClosedCount, Date_Requested AS Date
FROM Tickets_Closed
WHERE Date_Requested >='2018-01-01 00:00:00'
GROUP BY(Date_Requested)
)
SELECT
COALESCE(c.Date, o.Date) AS Date
, IFNULL(o.OpenCount, 0) + IFNULL(c.ClosedCount, 0) AS TotalOpen
, IFNULL(c.CountClosed, 0) AS CountClosed
FROM open o
FULL OUTER JOIN closed c ON o.Date = c.Date

SQL query for each ID in table

I have a query for 1 particular customer_id. How can I execute this query for each customer_id in table?
SELECT *
FROM table
WHERE date <= '2015-12-31 23:59:59' AND customer_id = 100
ORDER BY date DESC
LIMIT 1
You can use NOT EXISTS():
SELECT * FROM YourTable t
WHERE t.date <= '2015-12-31 23:59:59'
AND NOT EXISTS(SELECT 1 FROM YourTable s
WHERE t.customer_id = s.customer_id
AND t.date < s.date)
This will select only a record after the date filter where NOT EXISTS another record for the same id with a bigger date. Its basically the same as limit 1 for all.
You can use Inner join:
SELECT * FROM YourTable t INNER JOIN
(SELECT * FROM Table) s
ON t.customer_id = s.customer_id
WHERE t.date = '2015-12-31 23:59:59'
ORDER BY date DESC

SQL with multiple SELECT statement

Hi I have a bit of a problem with my SQL. My problem is when I filter the dates of my data, my SQL statement only returns 2 records which was the employee_id of the user.
This is the original statement of my working code that I have in filtering dates:
SELECT * FROM `rmguidef_prs`.`payment_report` WHERE DATE(`Report_Timestamp`) = DATE_ADD(CURDATE(), INTERVAL 24 HOUR) AND Employee_ID IN (
SELECT T1.Employee_ID from `rmguidef_prs`.`employee` T1
WHERE T1.Supervisor_ID = '".$id."')
OR Employee_ID = '".$id."'
This is the modified statement that I need the filters: (its working ok)
SELECT * FROM `report` WHERE Employee_ID IN (
SELECT T1.Employee_ID from `employee` T1
WHERE T1.Supervisor_ID = '".$id."')
OR Employee_ID IN (
SELECT T2.Manager_ID from `branches` T2
WHERE T2.Manager_ID = '".$id."')
OR Employee_ID = '".$id."'
But when I add this: DATE(Timestamp) = DATE_ADD(CURDATE(), INTERVAL 24 HOUR) in the statement to filter the date the only records shown are coming from this: OR Employee_ID = '".$id."'
SELECT * FROM `report` WHERE DATE(`Timestamp`) = DATE_ADD(CURDATE(), INTERVAL 24 HOUR) AND Employee_ID IN (
SELECT T1.Employee_ID from `employee` T1
WHERE T1.Supervisor_ID = '".$id."')
OR Employee_ID IN (
SELECT T2.Manager_ID from `branches` T2
WHERE T2.Manager_ID = '".$id."')
OR Employee_ID = '".$id."'
I want my modified SQL statement to be filtered by today's date, week, month, and past 3 months. I already have to code for those filters but I cannot figure out how to add those to my statement.
Add parenthesis to group criteria:
SELECT *
FROM `report`
WHERE DATE(`Timestamp`) = DATE_ADD(CURDATE(), INTERVAL 24 HOUR)
AND ( Employee_ID IN (SELECT T1.Employee_ID
FROM `employee` T1
WHERE T1.Supervisor_ID = '".$id."'
)
OR Employee_ID IN (SELECT T2.Manager_ID
FROM `branches` T2
WHERE T2.Manager_ID = '".$id."'
)
OR Employee_ID = '".$id."'
)
AND takes precedence over OR, so your date criteria was only being considered for the first of the three Employee_ID criteria.
Edit: After re-reading your question I'm not entirely sure if the above is what you're after, your date criteria would only return records with tomorrow's date, which probably doesn't exist in the Timestamp field, so that's probably the real problem.

Return results of query based on todays date in SQL (MySQL)

I have a query which I got help with but I am stuck on another bit.
The code I have is
SELECT a.name, COUNT(*) AS num FROM table2 b
INNER JOIN table1 a
ON b.status_id=a.id
GROUP BY status_id
What I would like to do now is only show the results if they have been entered on the current date? The date column is in table2. The format for the date column is date and time (eg 1341241153) which is automatically set by the CRM in this way. I am not sure what format this is in!
I only need to check if the date matches the current day. I hope that is clear.
This is a MySQL database.
Any help will be gratefully received!
Use this solution:
SELECT a.name, COUNT(*) AS num
FROM table2 b
INNER JOIN table1 a ON b.status_id = a.id
WHERE b.datecol >= UNIX_TIMESTAMP(CURDATE()) AND
b.datecol < UNIX_TIMESTAMP(CURDATE() + INTERVAL 1 DAY)
GROUP BY b.status_id
This will avoid wrapping your date column inside a function which would make the query non-sargable (i.e. not able to use indexes). By keeping the comparison on the bare date column, MySQL will still able to utilize an index(if you have it set up on the date column), and it should be quite efficient.
You could simplify it even further if you ABSOLUTELY KNOW that the date entered can never be sometime in the future (i.e. tomorrow or the next day):
SELECT a.name, COUNT(*) AS num
FROM table2 b
INNER JOIN table1 a ON b.status_id = a.id
WHERE b.datecol >= UNIX_TIMESTAMP(CURDATE())
GROUP BY b.status_id
The second conditional check is removed as it doesn't need to check if it's in a future day.
You should use from_unixtime() function on date column that holds values like 1341241153.
Because these values seem stored in unix timestamp format.
Example:
mysql> select
-> from_unixtime( 1341241153 ) as 'my_datetime_1341241153',
-> date( from_unixtime( 1341241153 ) ) as 'my_date_1341241153',
-> curdate(),
-> curdate() > date( from_unixtime( 1341241153 ) ) 'is_today_later?',
-> curdate() = date( from_unixtime( 1341241153 ) ) 'is_today_equal?',
-> curdate() < date( from_unixtime( 1341241153 ) ) 'is_today_before?'
-> from
-> dual
-> \G
*************************** 1. row ***************************
my_datetime_1341241153: 2012-07-02 20:29:13
my_date_1341241153: 2012-07-02
curdate(): 2012-07-15
is_today_later?: 1
is_today_equal?: 0
is_today_before?: 0
1 row in set (0.00 sec)
Your query should be:
SELECT a.name, COUNT(*) AS num FROM table2 b
INNER JOIN table1 a
ON ( b.status_id=a.id and curdate() = date( from_unixtime( b.crm_date_time_column ) ) )
GROUP BY status_id
Try this::
SELECT a.name, COUNT(*) AS num FROM table2 b
INNER JOIN table1 a
ON b.status_id=a.id
where DATE(column_date) = DATE(now())
GROUP BY status_id

Select the first element in each day of the month

How to select the first element of each day in a month with mysql query ?
I have table with offers - startdate, so i can check for each day,month,year i'm getting the element but, i'm wondering how to get only the first element in each day of some month ?
Assume the following
Table is called mytable
Table has id as primary key
Table has dt as datatime
You want the first id of everyday in February 2012
Try this:
SELECT B.id FROM
(
SELECT DATE(dt) date_dt,MIN(dt) dt
FROM mytable
WHERE dt >= '2012-02-01 00:00:00'
AND dt < '2012-03-01 00:00:00'
GROUP BY DATE(dt)
) A
LEFT JOIN mytable B USING (dt);
If any dt has multiple B.id values try this:
SELECT dt,MIN(id) id
(
SELECT B.id,B.dt FROM
(
SELECT DATE(dt) date_dt,MIN(dt) dt
FROM mytable
WHERE dt >= '2012-02-01 00:00:00'
AND dt < '2012-03-01 00:00:00'
GROUP BY DATE(dt)
) A
LEFT JOIN mytable B USING (dt)
) AA GROUP BY dt;
Assuming startdate is a DATETIME type, and the earliest entry is the one with the earliest DATETIME value, for March, 2012:
SELECT DISTINCT *
FROM tbl t1
LEFT JOIN tbl t2
ON (t2.startdate BETWEEN '2012-02-01 00:00:00' AND '2012-02-29 23:59:59')
AND t2.startdate < t1.startdate
WHERE (t1.startdate BETWEEN '2012-02-01 00:00:00' AND '2012-02-29 23:59:59')
AND t2.startdate IS NULL
If there are no duplicate dates, then you don't need the DISTINCT.
This query works by joining with any earlier record for the same month, so if nothing was joined, it's the earliest, through process of elimination.
This technique is explained in detail in the book SQL Antipatterns.
This could also be solved with subqueries, but this type of JOIN is supposed to be easier to optimize by MySQL than subqueries, which often negate the use of indexes.
without knowing the exact structure of your table something like this should work:
SELECT MIN(offerId) FROM offers WHERE startdate <= '2012-03-06' AND startdate >= '2012-02-06' GROUP BY date(startdate)
It sounds like you are trying to do something like the following:
SELECT col_1, date_col, col_3 FROM tbl
WHERE
date_col = ( SELECT min(date_col) FROM tbl
WHERE
year(date_col) = 2006 AND
month(date_col) = 02
);
This can also be used to find the max( date_col ) . Hope this helps.
Just to offer a different way to skin this cat (much easier in SQL Server for once actually)
SELECT
t0.offerId
FROM
offers AS t0 LEFT JOIN
offers AS t1 ON t0.offerId = t1.offerId AND t1.startDate > t0.startDate AND
(t0.startDate BETWEEN '2012-02-01' AND '2012-03-01') AND
(t1.startDate BETWEEN '2012-02-01' AND '2012-03-01')
WHERE
t1.col1 IS NULL;
If you have multiple rows with the same exact time you will get multiple values returned, which you can weed out in your application logic or with a sub-query. BTW this is called a groupwise minimum/maximum.