通过布尔列标志选择记录

时间:2019-03-28 19:11:31

标签: mysql sql

我有一张这样的桌子:

+----+--------------+-----------+------------+
| id | natural_id   | flag      | date       |
+----+--------------+-----------+------------+                                           
| 1  |           1  |  true     | 01/01/2000 |                                      
| 2  |           1  |  true     | 02/01/2000 |
| 3  |           1  |  false    | 03/01/2000 |
| 3  |           2  |  true     | 01/01/2000 |
| 4  |           2  |  false    | 02/01/2000 |
| 5  |           2  |  false    | 03/01/2000 |
+----+--------------+-----------+------------+

我正在尝试编写select,它将根据 first flag <来显示具有 natural_id date 的记录/ strong>假值:

+--------------+------------+
| natural_id   | date       | 
+--------------+------------+                                      
|           1  |  03/01/2000|                               
|           2  |  02/01/2000|
+---------------------------+

我不知道如何在SQL中执行此操作。在纯SQL中甚至可能吗?

3 个答案:

答案 0 :(得分:2)

您可以使用相关子查询:

select t.*
from table t
where t.id = (select t1.id
              from table t1
              where t1.natural_id = t.natural_id and t1.flag = 'false'
              order by t1.date
              limit 1
             );

答案 1 :(得分:2)

使用group by natural_id

select 
  natural_id,
  min(date) date
from tablename
where flag = 'false'
group by natural_id

如果标志的类型为BOOLEAN,则可以这样操作:

select 
  natural_id,
  min(date) date
from tablename
where not flag
group by natural_id

答案 2 :(得分:1)

SELECT natural_id,date
FROM
(SELECT natural_id,date,flag, ROW_NUMBER() OVER(PARTITION BY natural_id, 
       ORDER BY date ASC) AS RowNum
FROM table) A
WHERE RowNum =1 AND flag = 'false'