我有一张桌子
if age<6 or age>18:
print ("NA")
然后我有另一张桌子
Orders
ID User
-----------------
1 Matt
2 Chris
3 John
我的目标是创建一个查询,返回所有具有“开放”联系请求但没有响应的订单。一个响应足以满足多个请求。在日期时间之后没有响应的请求是“打开”的。我怎么能做到这一点?
在上面的场景中,我想返回
Order_Contact
ID Order_ID Type Timestamp
-------------------------------------------------------------------
1 1 Request 2018-01-01 10:00:00
2 1 Request 2018-01-01 10:35:00
3 1 Response 2018-01-01 11:00:00
4 1 Request 2018-01-01 12:00:00
5 2 Request 2018-01-01 13:00:00
6 2 Response 2018-01-01 14:00:00
答案 0 :(得分:3)
首先,获取每个订单的最新条目:
SELECT Type, MAX(ID)
FROM Order_Contact
GROUP BY Order_ID
然后,过滤&#34;打开&#34;输入:
SELECT *
FROM (
SELECT Type, MAX(ID)
FROM Order_Contact
GROUP BY Order_ID
) as max_id
WHERE max_id.Type = 'Request'
编辑:
上面的解决方案适用于我的MySQL安装,但以下解决方案甚至可以使用sqlfiddle(http://sqlfiddle.com/#!9/92ecd4/12):
SELECT *
FROM (
SELECT *
FROM Order_Contact
WHERE ID IN (
SELECT MAX(ID)
FROM Order_Contact
GROUP BY Order_ID
)
) as Reduced_Order_Contact
WHERE Reduced_Order_Contact.Type = 'Request'
编辑2:
对于问题的扩展,添加列是一个简单的连接:
SELECT Orders.ID, Orders.User
FROM (
SELECT *
FROM Order_Contact
WHERE ID IN (
SELECT MAX(ID)
FROM Order_Contact
GROUP BY Order_ID
)
) as Reduced_Order_Contact
INNER JOIN Orders
ON Reduced_Order_Contact.Order_ID = Orders.ID
WHERE Reduced_Order_Contact.Type = 'Request'
答案 1 :(得分:2)
检查此查询
select
Orders.ID, Orders.[User]
from (
select
*, max([Timestamp]) over (partition by Order_ID) maxDate
from
Order_Contact
) t
join Orders on t.Order_ID = Orders.ID
where
t.maxDate = t.[Timestamp]
and t.[Type] = 'Request'
由于问题中的更改而更新了查询