2012-01-10 32 views
1

我有一張表,其中包含借給用戶的計算機列表。每次機器退回時我們都會進行輸入。我用下面的語句由用戶,機器#,日期和動作選擇組中的條件數據

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 

我尋找幫助修改查詢只返回最近的一個項目,返回一個列表,並且只有當該機器當前不在時。

在此先感謝您提供的任何環境!

回答

3

可以使用inner join過濾掉每臺機器舊的行。一旦你有最新的行,where可以用來選擇「出」的機器。

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' 
+0

upvote for a correct answer,並糾正其他人的 – 2012-01-10 21:49:08

+0

像夢一樣工作。謝謝! – jimb0z 2012-01-11 08:23:37

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 
+0

這將返回最晚時間機器出去?不要以爲這是OP後 – Andomar 2012-01-10 21:36:07

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_outo.in_out按評論。

+0

應該工作,如果你改變'where i.in_out'到'where o.in_out' – Andomar 2012-01-10 21:37:11

+0

謝謝你指出我的錯誤。你是對的。我編輯了答案。 – 2012-01-10 21:39:36

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 

固定

+0

'InOut ='out''不應該在子查詢之外嗎? – Andomar 2012-01-10 21:35:18

+0

否。子查詢正在返回最近結帳的資產和日期。完整的查詢與主表連接以獲取整個記錄。但是,如果在特定日期有多次結帳,這可能會出現奇怪的現象。我需要根據真實的數據檢查結果,你可能是對的:) – 2012-01-10 21:38:51

+1

OP說「只有當該機器當前沒有。」目前形式的這個答案會顯示一臺機器在最新的「出」記錄後有一個「in」記錄。 – Andomar 2012-01-10 21:41:36

0

SELECT名稱,資產號,日期的InOut

FROM表,其中的InOut = '出' ORDER BY日期遞減