douyi4991 2014-05-28 11:02
浏览 124
已采纳

MSSQL获取id和四个日期的最小(最早)

I have a table in mssql (2005) which has four date columns in it and an ID column.

I would like to return the minimum date of all four columns and the associated id.

SELECT TOP 1 min(date1), min(date2), min(date3), min(date4)  FROM datatable
WHERE  date1 > CAST(? AS DATETIME) OR 
     date2 > CAST(? AS DATETIME) OR
     date3 > CAST(? AS DATETIME) OR
     date4 > CAST(? AS DATETIME) 

I'm then sorting the dates in php to give me the mimimum row. I can't work out how to add returning the id to this.

  • 写回答

2条回答 默认 最新

  • douxing1850 2014-05-28 11:06
    关注

    You can unpivot the columns into rows, then select the minimum using TOP 1 (as this allows you to also find out which one of the four columns was the minimum):

    SELECT  t.ID, upvt.Date, upvt.ColumnName
    FROM    Datatable AS t
            CROSS APPLY
            (   SELECT  TOP 1 ColumnMame, Date
                FROM    (VALUES 
                            ('Date1', Date1),
                            ('Date2', Date2),
                            ('Date3', Date3),
                            ('Date4', Date4)
                        ) AS d (ColumnName, Date)
                ORDER BY d.Date 
            ) AS upvt
    

    EDIT

    Just seen this is SQL Server 2005, so you can't use a table valued constructor to unpivot the data, you will need to use SELECT and UNION ALL

    SELECT  t.ID, upvt.Date, upvt.ColumnName
    FROM    Datatable AS t
            CROSS APPLY
            (   SELECT  TOP 1 ColumnMame, Date
                FROM    (   SELECT Columnname = 'Date1', Date = Date1 UNION ALL
                            SELECT Columnname = 'Date2', Date = Date2 UNION ALL
                            SELECT Columnname = 'Date3', Date = Date3 UNION ALL
                            SELECT Columnname = 'Date4', Date = Date4
                        ) AS d
                ORDER BY d.Date 
            ) AS upvt;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line