0

我有下表。

   ID SampleID SampleState Date
1   A1   First 1/10/2013
2   A1   Second 1/11/2013
3   A1   Last   1/12/2013
4   A2   First  1/10/2013
5   A2   Closed 1/11/2013
6   A3   First  1/10/2012
7   A3   Second 1/10/2012

我必须使用以下规则拉出行。

a.) Display the lowest date of each SampleID provided the date is more than 10 days from current day
b.) Display the latest state of each SampleID.
c.) Do not display the SampleID if any of the state of the SampleID is Closed

例如,对于这个表,输出应该是

    SampleID SampleState Date
     A1   Last   1/10/2013
     A3   Second 1/10/2012

我的查询未显示所有结果。

SELECT  a.SampleID,a.SampleState,b.date
FROM    ListOfStates 
        INNER JOIN
        (
            SELECT  ID,SampleID, Max(ID) Max_ID, SampleState
            FROM    ListOfStates 
            GROUP   BY SampleID
        ) a 
    on a.Max_ID = ListOfStates.ID
        INNER JOIN
        (
            SELECT  ID,SampleID, Min(ID) min_ID, date
            FROM    ListOfStates 
            GROUP   BY SampleID
        ) b
on b.min_ID = ListOfStates.ID

where              

 b.Date  < DATE_SUB(CURDATE(), INTERVAL 10 DAY)
and a.SampleState !='Closed'
4

1 回答 1

1

以下内容将您的条件放入单个查询中:

select SampleId,
       min(case when t.Date < DATE_SUB(CURDATE(), INTERVAL 10 DAY) then date end) as MinDate,
       max(case when t.date = tsum.maxDate then state end) as MostRecentState
from t join
     (select SampleId, max(date) as maxDate
      from t
      group by SampleId
     ) tsum
     on t.SampleId = tsum.SampleId
group by SampleId
having max(case when state = 'Closed' then 1 else 0 end) = 0 and
       min(date) < DATE_SUB(CURDATE(), INTERVAL 10 DAY)

我认为关键是条件聚合。case您可以使用子句中的语句聚合事物,而不是使用子句(或子句)select进行过滤。wherehaving

于 2013-02-05T01:59:57.307 回答