我有下表。
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'
答案 0 :(得分: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
语句聚合事物,而不是使用where
子句(或having
子句)进行过滤。