Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIN( ) with conditions? MySQL

Tags:

mysql

So I have a table with a few columns and I'm doing a GROUP BY. In addition to getting other columns I want to get the MIN() value of one column when the other column is NULL. Here's what I have so far:

Table columns:

id        INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
table2_id INT(11) UNSIGNED NOT NULL,
iteration INT(11) UNSIGNED,
timestamp INT(11) UNSIGNED NOT NULL

SQL:

SELECT
    table2_id,
    COUNT(id) as total,
    COUNT(iteration) as completed,

    # I want the MIN(timestamp) but only when
    # iteration IS NULL
    MIN(timestamp) as next_incomplete
FROM
    table1
GROUP BY
    table2_id
like image 522
chrislondon Avatar asked Mar 27 '13 20:03

chrislondon


People also ask

Can we use MIN function in WHERE clause?

You can get the lowest or minimum value using this function from any column, even you can filter the lowest or minimum value between specified expressions using the WHERE clause.

How does MySQL calculate minimum?

MySQL MIN() Function The MIN() function returns the minimum value in a set of values.

How do you find min excluding 0 in SQL?

In MySQL you can use the NULLIF function. NULLIF will compare the price value with 0 and if it's true, it will return null.

How do I find the minimum and maximum values in MySQL?

MySQL MIN() and MAX() FunctionsThe MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


1 Answers

Use this for the MIN expression:

MIN(CASE WHEN iteration IS NULL THEN timestamp END) as next_incomplete
like image 100
Ed Gibbs Avatar answered Oct 11 '22 00:10

Ed Gibbs