从另一个 table 获取用户的最大日期
Get max date for user from another table
我有两个 table,一个 table 我正在存储用户状态,在第二个日志中。
“状态”table
id , customerId, userName, serviceId, status
“日志”table
id, customerId, logDate, status
我需要为每个客户获取特定日期间隔(从 2020-10-01 到 2020-11-31)和特定状态(状态 = 6)的最新日志。所有客户日志都存储在“日志”table.
这是我试过但没有成功的方法:
Select distinct (a.customerId), a.userName, a.serviceId, a.status, max(logDate)
FROM status a
JOIN logs b
WHERE logDate BETWEEN '2020-10-01' AND '2020-11-31' and a.customerId = b.customerId and a.status = 6 group by b.logDate
如有任何帮助,我们将不胜感激。
您的 group by
子句已关闭:您需要按所有非聚合列进行分组。
select s.customerid, s.username, s.serviceid, s.status, max(l.logdate) as maxlogdate
from status s
inner join logs l
where
l.logdate >= '2020-10-01'
and l.logdate < '2020-12-01'
and l.customerid = s.customerid
and s.status = 6
group by s.customerid, s.username, s.serviceid, s.status
一些数据库只支持将status
table 的主键放在group by
子句中。假设是 customerid
:
group by s.customerid
请注意,我将查询更改为使用 有意义的 table 别名。
我有两个 table,一个 table 我正在存储用户状态,在第二个日志中。
“状态”table
id , customerId, userName, serviceId, status
“日志”table
id, customerId, logDate, status
我需要为每个客户获取特定日期间隔(从 2020-10-01 到 2020-11-31)和特定状态(状态 = 6)的最新日志。所有客户日志都存储在“日志”table.
这是我试过但没有成功的方法:
Select distinct (a.customerId), a.userName, a.serviceId, a.status, max(logDate)
FROM status a
JOIN logs b
WHERE logDate BETWEEN '2020-10-01' AND '2020-11-31' and a.customerId = b.customerId and a.status = 6 group by b.logDate
如有任何帮助,我们将不胜感激。
您的 group by
子句已关闭:您需要按所有非聚合列进行分组。
select s.customerid, s.username, s.serviceid, s.status, max(l.logdate) as maxlogdate
from status s
inner join logs l
where
l.logdate >= '2020-10-01'
and l.logdate < '2020-12-01'
and l.customerid = s.customerid
and s.status = 6
group by s.customerid, s.username, s.serviceid, s.status
一些数据库只支持将status
table 的主键放在group by
子句中。假设是 customerid
:
group by s.customerid
请注意,我将查询更改为使用 有意义的 table 别名。