简体   繁体   English

使用Joins MySQL从表显示特定记录

[英]Display specific records from table using joins mysql

I have the following table. 我有下表。

   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

I have to pull out the rows using the following rule. 我必须使用以下规则提取行。

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

For example, For this table, the output should be 例如,对于此表,输出应为

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

My query doesn't display all the results. 我的查询未显示所有结果。

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'

The following takes your conditions and puts them into a single query: 以下内容将您的条件放入单个查询中:

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)

I think the key is the conditional aggregations. 我认为关键是条件聚合。 You can aggregate things using the case statement in the select clause, rather than filtering using where clause (or having clause). 您可以在select子句中使用case语句来聚合内容,而不是使用where子句(或having子句)进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM