我有一个表,其中包含一些借给用户的计算机列表。每次退回机器时都会输入一个条目。我使用以下语句按用户,机器#,日期和操作
返回列表SELECT Name, Asset#, Date, InOut
FROM Table
ORDER BY Asset#, date asc
返回
Name Asset# Date InOut
Jimmy BER210 2009-05-08 out
Jimmy BER210 2009-06-08 in
Jimmy BER210 2009-07-08 out
Sam BER220 2009-05-08 out
Sam BER220 2009-06-08 In
Jack BER230 2009-05-08 out
Jack BER230 2009-06-08 In
Jack BER230 2009-07-08 out
我正在寻找帮助修改该查询以仅返回最近的条目,并且仅在该机器当前已退出时。
提前感谢您提供的任何帮助!
答案 0 :(得分:3)
您可以使用inner join
过滤掉每台计算机的旧行。获得最新行后,可以使用where
选择“out”的计算机。
select Name, Asset#, Date, InOut
from Table t
join (
select Asset#
, max(Date) as MaxDate
from Table
group by
Asset#
) filter
on filter.Asset# = t.Asset#
and filter.MaxDate = t.Date
where t.InOut = 'Out'
答案 1 :(得分:1)
select Name, Asset#, Date, InOut
from Table
natural join (
select Asset#, max(Date) as Date
from Table
group by Asset#
)
where InOut = 'out'
order by date desc
固定
答案 2 :(得分:0)
在SQLServer中
SELECT TOP 1 Name, Asset#, Date, InOut
FROM Table
WHERE InOut = 'out'
ORDER BY Date DESC
在MySQL中
SELECT Name, Asset#, Date, InOut
FROM Table
WHERE InOut = 'out'
ORDER BY Date DESC
LIMIT 1
答案 3 :(得分:0)
SELECT Name, Asset#, Date, InOut
FROM Table o
WHERE Date = (select max(Date) from
Table i
where i.Asset# = o.Asset#
)
)
where o.in_out = 'out'
ORDER BY Asset#, date asc
修改根据评论将i.in_out
更改为o.in_out
。
答案 4 :(得分:0)
SELECT Name,Asset#,Date,InPut
FROM表WHERE InOut ='out'ORDER BY date desc