问题
I have a working query that counts all distinct values from table LDS where STATUS = 'OK' AND DATE >= '2012' AND if there are multiple identical IDs then count the one with the newest date if this id has a status of "ok":
COUNT(DISTINCT lds1.ID) FROM LDS lds1 LEFT JOIN LDS lds2 ON lds1.ID = lds2.ID AND lds1.Date < lds2.Date AND lds1.Status = 'ok' WHERE lds1.Date >= '2012' AND lds1.Status = 'ok' AND lds2.ID IS NUL
I now need to add another condition to be TRUE before the above query is run: "only consider IDs where STATUS=NULL AND DATE>= 2011". The initial ID instance with STATUS = NULL is not to be counted in the results; it just determines if an ID should even be considered.
Table LDS: ID | STATUS | DATE 1 | NULL | 2011 1 | ok | 2012 2 | bad | 2012 1 | bad | 2013 3 | NULL | 1999 3 | ok | 2012 4 | ok | 2012 5 | NULL | 2011 5 | ok | 2012 6 | NULL | 2012
The expected result of the full query is ID "5".
UPDATE:
Maybe this can be solved with arrays?
1. take all IDs from table LDS where STATUS=NULL AND DATE>=2011 and put into array (result: ID1, ID5, ID6)
2. For each ID in the array, check all instances in the table and select the one with the largest date AND STATUS IS NOT NULL (result: ID1, ID5)
3. Count how many of these have a STATUS=OK (result: ID5)
回答1:
COUNT(DISTINCT lds1.ID)
FROM
LDS lds1
LEFT JOIN LDS lds2
ON (lds1.ID = lds2.ID)
WHERE
lds1.Date = '2012-01-01'
AND lds1.Status = 'ok'
AND lds2.ID IS NOT NULL
try to use where clause for conditions
回答2:
I believe I have found an answer. Maybe someone could verify this.
COUNT DISTINCT ID FROM lds WHERE ID in ( COUNT(DISTINCT lds1.ID) FROM LDS lds1 LEFT JOIN LDS lds2 ON lds1.ID = lds2.ID AND lds1.Date<lds2.Date AND lds1.Status = 'ok' WHERE lds1.Date>='2012' AND lds1.Status = 'ok' AND lds2.ID IS NUL ) AND DATE>='2011' AND STATUS=NUL
来源:https://stackoverflow.com/questions/10055244/mysql-query-nested-where-clauses