【问题标题】:SQL: Take the oldest date from a table like [ date_year, date_month, date_day ]SQL:从像 [ date_year, date_month, date_day ] 这样的表中获取最早的日期
【发布时间】:2017-07-13 14:03:04
【问题描述】:

我有一张名为 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 查询 strong>最古老的专辑

(如果月和日的值为空也可以)

我不能使用 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

我该如何解决?谢谢

【问题讨论】:

  • 为什么不能使用 LIMIT ?
  • 不需要按年、月、日按国家、专辑(非聚合字段)顺序分组吗 1
  • @ValentinGenevrais LIMIT 已在 SQL:2008 中标准化。例如,它在 SQL Server 2000/2005 中不存在,在 Oracle 中也不存在。
  • NULL 表示指定时间段的开始还是结束?
  • @JeffUK(我认为)null 表示一个月的第一天和一年的第一个月

标签: mysql sql database postgresql musicbrainz


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    没有对此进行测试,如果它有效,我会感到惊讶。而不是 right 你应该使用 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
    

    【讨论】:

    • 感谢@JeffUK 的回答,但我只能使用标准 SQL 结构。例如,我不能使用 concat
    • Concat 不是标准的?哇。你可以使用|| 我无法测试,因为 SQL Server 不支持它。
    • 是 INSERT() 标准 ANSI smallsql.de/doc/sql-functions/string/insert.html 吗?我没有手头的标准.. 它会接受 int 而不是第一个字符串吗?
    • @ralph 现在怎么样? CAST 在 1992 年标准中;我更喜欢我的其他答案,但有选择也很好。
    • 练习设置为在不使用任何函数的情况下训练和理解机制
    猜你喜欢
    • 1970-01-01
    • 2021-03-19
    • 2011-07-12
    • 1970-01-01
    • 2016-04-13
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    相关资源
    最近更新 更多