简体   繁体   中英

Select a column only if id is distinct MySQL

I have the following table:

  AMAZON_ID  |    DATE    |  STATUS
   1         | 01/03/2014 |  Pending
   1         | 01/03/2014 |  Shipped
   2         | 01/04/2014 |  Pending
   3         | 01/05/2014 |  Cancelled
   4         | 01/06/2014 |  Pending

How can I select the earliest date from table where status is equals Pending where the count of id is not more then one, it should be like the following:

  AMAZON_ID  |    DATE    |  STATUS
   2         | 01/04/2014 |  Pending

I can not figure that out, this is what I have so far but its not working:

SELECT date
FROM table
WHERE status = 'Pending'
      AND COUNT(id) < 2
ORDER BY date ASC
LIMIT 1;

Use a subquery to GROUP BY the id 's that have COUNT of 1. Make sure your id is IN the results of this subquery, with a status of pending. Then ORDER BY date and LIMIT to the first result.

SELECT date
FROM table
WHERE
  status = 'Pending' AND
  id IN (
    SELECT id
    FROM table
    GROUP BY id
    HAVING COUNT(*) = 1
  )
ORDER BY date ASC
LIMIT 1;

One thing you can do is use a WHERE IN, and use a select statement to populate the WHERE clause with distinct ids

 SELECT date
            FROM table
            WHERE status = 'Pending'
            AND id IN (SELECT DISTINCT id FROM table)
            ORDER BY date ASC
            LIMIT 1;

It depends on what you really mean by "count of id is not more than one" .

I have renamed your column date to ts to make the queries valid SQL (as DATE is a SQL function so it may confuse parsers). See the SQL fiddle for the complete schema I used and the example queries .

Option 2: one row per ID total

In this case you have a problem because you want a query to get one piece of information (the minimum date) that is based on a different piece of information about the same table. This means that you need to queries, luckily you can just join the data of the two queries and filter appropriately.

SELECT data.id, status, MIN(ts)
FROM data
    JOIN (SELECT id, COUNT(*) AS amount FROM data GROUP BY id) AS totals
     ON totals.id = data.id
WHERE
    status = "Pending"
    AND totals.amount < 2
GROUP BY data.status;

Option 1 (easy): only one pending row per ID

NOTE : this answer does not answer the OP's question

In this case, the situation is quite easy as you can just filter all your rows with status "pending" , the minimum date and the total amount of rows that match your result and, after the aggregation (ie: using HAVING ) filter those that have less than 2 amounts.

In SQL that would be:

 
 
 
 
  
  
  SELECT id, status, MIN(ts) AS minTS, COUNT(*) AS amount FROM data WHERE status = "Pending" GROUP BY id, status HAVING amount < 2
 
 
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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