仅选择具有特定值的最新行

时间:2019-01-08 09:48:30

标签: mysql

表格:

person | borrow_date  | is_borrowed | SN | date        | id
1      | 2019-01-10...| 1           | 20 |2019-01-10...| 6
3      | 2019-01-09...| 3           | 10 |2019-01-09...| 5
1      | 2019-01-08...| 1           | 10 |2019-01-08...| 4
2      | 2019-01-08...| 1           | 10 |2019-01-08...| 3
1      | NULL         | 2           | 20 |2019-01-07...| 2
1      | NULL         | 2           | 10 |2019-01-07...| 1

我想要的输出是选择“ is_borrowed”等于1并按SN分组的最新行,这样,当使用person = 2或person = 3执行查询时,它将检索空集。而对于person = 1,它将返回两行。 想要的输出(其中person = 1):

person | borrow_date  | is_borrowed | SN | date         |id
1      | 2019-01-10...| 1           | 20 | 2019-01-10...|6
1      | 2019-01-08...| 1           | 10 | 2019-01-08...|4

想要的输出(其中person = 2):

EMPTY SET

想要的输出(其中person = 3):

EMPTY SET

这是我当前的查询,可惜它无法正常工作。

SELECT a.SN, a.is_borrowed,a.max(date) as date, a.person
FROM table a
INNER JOIN (SELECT SN, MAX(date) as date, osoba from table where person like 
"2"  group by SN) as b
ON a.SN=b.SN and a.date=b.date
WHERE a.person like "2" and a.is_borrowed=1

1 个答案:

答案 0 :(得分:1)

如果我根据问题及其下的评论正确地理解了您,则这是一种无需指定人员的方式:

select * 
from TableName as p 
inner join (select max(borrow_date) as borrow_date,
                   SN 
            FROM TableName
            where is_borrowed = 1 
            group by SN) as p2
on p.borrow_date = p2.borrow_date and p.SN = p2.SN

这应该为您提供所需的结果。这是demo

请注意,我必须更改表中的borrowed_date值,因为您的值包含小时和分钟,而我没有添加这些值。

您总是可以通过在联接之后添加一个where子句来为每个人指定它。

select p.person, 
       p.borrow_date, 
       p.is_borrowed, 
       p.SN, 
       p.date, 
       p.id 
from TableName as p 
inner join (select max(borrow_date) as borrow_date,
                   SN 
            FROM TableName
            where is_borrowed = 1 
            group by SN) as p2
on p.borrow_date = p2.borrow_date and p.SN = p2.SN
where p.person = '1'

输出:

person | borrow_date  | is_borrowed | SN |  date        | id
1      |  2019-01-10  |     1       | 20 |  2019-01-10  | 6   
1      |  2019-01-08  |     1       | 10 |  2019-01-08  | 4   

where p.person = '2'where p.person = '3'会返回空集。

相关问题