嗨,我有一个像这样的桌子:
SN | User | is_borrowed | date
105 | 1 | 1 |2019-1-1
105 | 1 | 0 |2019-2-1
105 | 1 | 1 |2019-3-1
106 | 2 | 1 |2019-4-1
107 | 1 | 1 |2019-5-1
106 | 2 | 0 |2019-6-1
106 | 2 | 1 |2019-8-1
107 | 1 | 0 |2019-9-1
107 | 2 | 1 |2019-10-1
想要的输出将显示借用的内容(未返回),并且user = 1:
SN | User | is_borrowed | date
105 | 1 | 1 |2019-3-1
User = 2的输出并借用(未返回):
SN | User | is_borrowed | date
106 | 2 | 1 |2019-8-1
107 | 2 | 1 |2019-10-1
总而言之,我想要一个当前借用的设备列表,这些设备未为每个用户返回。可悲的是,我什么都没想到:/
答案 0 :(得分:0)
期待您的预期结果似乎是您正在为SN(is_borrowed = 1的用户)寻找max(date)
select SN, user, is_borrowed, max(date)
from my_table
where is_borrowed = 1
group by SN, user, is_borrowed
或实际借用的设备
Select * from my_table m
inner join t (
select SN, is_borrowed, max(date) max_date
from my_table
where is_borrowed = 1
group by SN, is_borrowed
) t on t.SN = m.SN AND t.max_date = m.date
答案 1 :(得分:0)
SELECT t.sn, t.user, t.is_borrowed, t.date
FROM TABLE_NAME t
WHERE t.is_borrowed = 1
AND t.date =
(
SELECT MAX(x.date)
FROM TABLE_NAME x
WHERE x.user = t.user
)
AND (
SELECT xx.is_borrowed
FROM TABLE_NAME xx
WHERE t.sn = xx.sn
AND t.date < xx.date
) <> 0
;