簡體   English   中英

SQL:從類似[date_year,date_month,date_day]的表格中獲取最早的日期

[英]SQL: Take the oldest date from a table like [ date_year, date_month, date_day ]

我有這張桌子叫做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查詢,該查詢使用唱片集名稱,國家/地區名稱最舊唱片集日期(年,月,日)

(如果month和day的值為空也可以)

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

我該如何解決? 謝謝

如果沒有對此進行測試,如果它起作用我會感到驚訝。 您可能應該使用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

這應該可行,最終您要做的就是以可排序的格式構建日期,然后按日期排序。

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); date字段的所有引用替換為coalesce(date_foo,0);coalesce(date_foo,99);取決於您要如何對待它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM