0

以下 SQL 查询将返回我所有处于开发或已完成模式的程序。这里的目标是获取所有程序的最新状态。

我使用以下查询返回我的所有程序状态

SELECT PK_ProgramState, FK_Program, State
FROM ProgramStates

我得到以下结果:

程序状态

正如该图像彩色矩形中的黄色高亮所示,我希望返回那些“FK_Program”记录。不需要最后一个突出显示的记录状态之前的其他人。

我似乎不知道该怎么做……我一直在尝试的所有查询都给了我虚假的结果。感谢所有帮助。

提前致谢。

4

5 回答 5

4
SELECT s1.PK_ProgramStatee, s1.FK_Program, s1.State
FROM ProgramStates s1
inner join
(
  SELECT max(PK_ProgramState) as mstate, FK_Program
  FROM ProgramStates
  group by FK_Program
) s2 on s2.mstate = s1.PK_ProgramState and s2.FK_Program = s1.FK_Program
于 2013-08-23T14:06:14.430 回答
1

这是一种方法:

select fk_program
from ProgramStates ps
group by fk_program
having substring_index(group_concat(State order by PK_ProgramState desc), ',', 1
                      ) in ('Development', 'Completed');

这是使用group_concat()然后将其与您要查找的状态进行比较来查找最后一个状态。

你也可以把having子句写成:

having group_concat(State order by PK_ProgramState desc) like 'Completed%' or
       group_concat(State order by PK_ProgramState desc) like 'Development%'

这种形式的意图可能更清楚。

于 2013-08-23T14:07:01.450 回答
1

尝试这个:

SELECT DISTINCT FK_Program, 
    (SELECT TOP(1) State FROM ProgramStates P1 
    WHERE P1.FK_Program = ProgramStates.FK_Program 
    ORDER BY PK_ProgramState DESC) as State
FROM ProgramStates
于 2013-08-23T14:08:57.100 回答
1
select p.fk, (select ps.state from ProgramStates ps
              where ps.FK_Program = p.fk
              order by ps.PK_ProgramState desc limit 1)

from (select distinct q.FK_Program as fk
from ProgramStates q) as p

http://sqlfiddle.com/#!2/422d92/19

于 2013-08-23T14:18:38.003 回答
1
    select 
    ps.PK_ProgramState, 
    ps.FK_Program,
    ps.state
from 
    ProgramStates ps
inner join

    (select max(PK_ProgramState)PK_ProgramState, FK_Program from ProgramStates  group by FK_Program) stg
    on stg.FK_Program=ps.FK_Program and stg.PK_ProgramState=ps.PK_ProgramState
于 2013-08-23T14:24:28.587 回答