SQL查询:与条件比较

时间:2014-03-15 22:19:27

标签: sql filter comparison conditional-statements

我的表格如下(简化):

名称|状态
app-1 |启动
app-1 |运行
app-1 |运行
app-1 |运行
app-1 |完成
app-2 |启动
app-2 |运行
app-2 |跑

现在,我想过滤所有已启动状态且没有“完成”的应用。对于上面的示例,结果应该是“app-2”。

我不知道如何进行比较,同时另外使用条件......这真的给了我一些困难时间。我希望有人可以帮助我吗?!

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT * FROM table_name
WHERE status = 'run' and name NOT IN
  (SELECT name FROM table_name WHERE status = 'finish')

答案 1 :(得分:0)

不确定您使用的是哪个关系数据库,但查询类似:

Select AppStatus.Name
From (
      Select Name, Started, Finished
      Sum(Case When status = 'start' then 1 else 0 end) as Started,
      Sum(Case When status = 'finish' then 1 else 0 end) as Finished,
      From Table
      Group By Name
) as AppStatus
Where AppStatus.Started > 0 and AppStatus.Finished > 0

更新: 如果你假设所有行都以一个开始开始,并且有零个或多个运行然后结束,那么这也会有效并且更加简单!

Select Distinct(Name) 
From Table Where Name Not In (
    SELECT Name
    FROM Table
    WHERE Status = 'finish')

答案 2 :(得分:0)

select name from _table t1
  where t1.status = 'start'
    and not exists (
      select name from _table t2
         where t1.name = t2.name
          and t2.status = 'finish'
     )