SQL:从[date_year,date_month,date_day]

时间:2017-07-13 14:03:04

标签: mysql sql database postgresql musicbrainz

我有一个名为RELEASE的表:

*Country, Album, Date_year, Date_month, Date_day*
  Italy    Z      1940       2           27
  Italy    Y      1992       11          22
  Italy    X      1940       1           20
  Italy    R      1998       null        null
  France   W      1944       9           18
  UK       L      1989       8           21
  UK       P      1970       10          1
  Germany  E      2002       null        null

我需要指定一个SQL查询,该查询采用相册名称国家/地区名称日期(年,月,日)最古老的专辑

(如果月和日的值为空,也没关系)

我不能使用 LIMIT,OFFSET,ROWNUM ...我只能使用标准的SQL结构。

我尝试进行此查询,但不正确

SELECT country, album, min(date_year), min(date_month), min(date_day)
FROM release

结果将是:

 *Country, Album, Date_year, Date_month, Date_day*
  Italy    X      1940       1           20

我怎么解决?感谢

2 个答案:

答案 0 :(得分:0)

没有对此进行测试,如果有效,我会感到惊讶。而不是你应该使用mid(8,len())h(因为左边总是8个字符)

SELECT 
    release.country, 
    right(
        min(

                cast(Date_year as nvarchar)+  cast(Date_month as nvarchar) + cast(Date_Day as varchar) +album
        ),1) Album,
     min(cast(Date_year as nvarchar)+  cast(Date_month as nvarchar) + cast(Date_Day as varchar) +album) minDate
from release
group by country

答案 1 :(得分:0)

这应该有效,最终您需要做的就是以可排序的格式构建日期,然后按它排序。

select release.country, Album, Date_Year, Date_Month, Date_Day from RELEASE

left join
(
        select country, 
               min(date_year*10000+date_month*100+date_day) minDay 
        from RELEASE
        group by country) albumDay

on albumDay.country = RELEASE.country

where 
date_year*10000+date_month*100+date_day = minDay

附带条件是,如果您有多张“最早的”专辑,则会显示所有最旧的专辑。问题陈述没有说明如何处理这个问题。

您需要添加NULL处理(使用coalesce(date_foo,0);coalesce(date_foo,99);替换对日期字段的每个引用,具体取决于您希望如何处理它们。