如何解决如何在mysql中找到最后一个用户?
用户:
Private Sub Form_Current()
TempVars!CurrentItemNumber.Value = [ItemNumber].Value
Dim ctrl As control
For Each ctrl In Me.Controls
If ctrl.Name = "OptionLabel1" Then
If DLookup("[SecLevel]","Switchboard Items",TempVars!CurrentItemNumber.Value) = "Admin" Then
Me.OptionLabel1.ForeColor = RGB(255,0)
ElseIf DLookup("[SecLevel]",TempVars!CurrentItemNumber.Value) = "Operator" Then
Me.OptionLabel1.ForeColor = RGB(0,255)
Else
Me.OptionLabel1.ForeColor = RGB(0,0)
End If
End If
Next
End Sub
订单:
userid apartment_id blockid flat_id
1002 2 3 101
1004 1 4 102
1005 2 3 101
现在我想要以下内容:
orderid userid order_date
10 1002 2020-07-11
11 1004 2020-08-13
12 1005 2020-09-11
我已经编写了用于查找除“ last_order_user_id”之外的所有这些内容的sql。有人可以帮我吗?这是我到目前为止所拥有的:
apartment_id blockid flat_id no_of_users last_order_date last_order_user_id
2 3 101 2 2020-09-11 1005
我尝试将o.userid添加到select语句的字段列表中,但是由于orders表是由order_date按升序排序的,因此它返回第一个已排序的用户ID。
任何建议都会很有帮助。
解决方法
您需要计算每个公寓/街区/公寓组合的最大订购日期;然后您可以将其重新连接到订单和用户表,以查找下一个订单的用户:
SELECT u.apartment_id,u.blockid,u.flat_id,m.no_of_users,m.last_order_date,u.user_id AS last_order_user_id
FROM users u
JOIN orders o ON u.user_id = o.user_id
JOIN (
SELECT apartment_id,blockid,flat_id,COUNT(DISTINCT u.user_id) AS no_of_users,MAX(o.order_date) AS last_order_date
FROM users u
JOIN orders o ON u.user_id = o.user_id
GROUP BY apartment_id,flat_id
) m ON m.apartment_id = u.apartment_id
AND m.blockid = u.blockid
AND m.flat_id = u.flat_id
AND m.last_order_date = o.order_date
输出:
apartment_id blockid flat_id no_of_users last_order_date last_order_user_id
1 4 102 1 2020-08-13 1004
2 3 101 2 2020-09-11 1005
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。