MariaDB Select Min-Date (earliest) from multiple columns

255 Views Asked by At

I need to do a select within a MariaDB, where I have one row per customer and the earliest date out of three different tables with action datetime values.

Example Tables:

Main Table

customer-id Column_X
First Things
Second Things

Table One

customer-id Date
First Date
Second Date

Table Two

customer-id Date
First Date
Second Earliest Date (Table2)

Table Three

customer-id Date
First Earliest Date (Table3)
Second Date

My aim is to have the earliest date out of the three columns in the other tables in one column within the select.

What I tried to do is this:

SELECT main.customer-id , main.Column_X 
    (SELECT LEAST(C) FROM (VALUES ((table1.date) , (table2.date), (table3.date)) AS C) AS First_Action
FROM main_table main
LEFT JOIN table_one table1 ON table1.cutomer-id = main.customer-id
LEFT JOIN table_two table2 ON table2.cutomer-id = main.customer-id
LEFT JOIN table_three table3 ON table3.cutomer-id = main.customer-id
GROUP BY main.customer-id;

Unfortunatly, I don't get any results just an error message.

So the resulting table should look something like this:

Result

customer-id Column_X First_Action
First Things Earliest Date (Table 3)
Second Things Earliest Date (Table 2)

I just started working with SQL statments and therefore have basically no experience. Help would be much appreciated!

Many Greetings Chris

1

There are 1 best solutions below

0
Ankit Bajpai On

It seems you simply need a LEAST function -

SELECT main.customer-id , main.Column_X,
       LEAST(table1.date, table2.date, table3.date) AS First_Action
  FROM main_table main
  LEFT JOIN table_one table1 ON table1.cutomer-id = main.customer-id
  LEFT JOIN table_two table2 ON table2.cutomer-id = main.customer-id
  LEFT JOIN table_three table3 ON table3.cutomer-id = main.customer-id;