[英]MySql : Get data from two tables
I am stuck with mysql query.Not able to proceed. 我被mysql查询卡住了。无法继续。
I have 2 tables where user's login time is recorded.Login time should be considered when either of the table contains entry. 我有2个记录用户登录时间的表。当其中一个表包含条目时,应考虑登录时间。 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 例如:count = 0记录了employee1
on 1-Jan-2017 in table1 & table2 <- count++ (if he logs in 2 tables then only 1 count should be considered) 在2017年1月1日在table1&table2 <-count ++中(如果他登录2个表,则仅应考虑1个计数)
on 2-Jan-2017 in table1 <- count++ 于2017年1月2日在table1 <-count ++中
So for employee1 count is 2 因此,对于employee1,计数为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.