0

I am working with SQL in R. I want to get the minimum date by choosing the minimum value of the column 'day;, the minimum value of the column 'month' and the minimum value of the column 'year'.

I have tried this by the following code:

dbGetQuery(db, "SELECT day, month, year
                FROM surveys
                WHERE year = (SELECT MIN(year) FROM surveys);")

But my output is not one value, how can I get one value in my output and not a list of values?

Parfait
  • 104,375
  • 17
  • 94
  • 125
Elaji
  • 17
  • 4

2 Answers2

0

Using the test data shown we order it by year, month and day and select the first row of the sorted table.

library(sqldf)
surveys <- data.frame(year = 2001:2005, month = 5:1, day = 1:5)

sqldf("select day, month, year from surveys order by year, month, day limit 1")
##   day month year
## 1   1     5 2001
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

Right now your query returns rows on the minimum year, not minimum date. Consider generating a date column by concatenating the date parts to identify minimum:

sql = "WITH sub AS (
          SELECT day, month, year
                , DATE(year || '-' ||
                       CASE 
                          WHEN length(month)=1 
                          THEN '0' || month
                          ELSE month
                       END  || '-' ||
                       CASE 
                          WHEN length(day)=1 
                          THEN '0' || day 
                          ELSE day 
                       END) AS [date]
          FROM surveys
      )

      SELECT DISTINCT day, month, year, [date]
      FROM sub
      WHERE [date] = (SELECT MIN([date]) FROM sub)"

dbGetQuery(db, sql)

Online Demo

Parfait
  • 104,375
  • 17
  • 94
  • 125