获取几列之间的最小值 [英] Get the minimum value between several columns

查看:146
本文介绍了获取几列之间的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SQL Server 2008;



假设我有一个表'X',列'Date1','Date2','Dateblah',全部键入DateTime。



我想选择三列之间的最小值,例如(简化,日期为mm / dd / yyyy)

  ID Date1 Date2 Dateblah 
0 09/29/2011 09/20/2011 09/01/2011
1 01/01 / 2011 01/05/2011 03/03/2010

ID MinDate
0 09/01/2011
1 03/03/2010

有没有一个面包和黄油指令来做到这一点?



提前感谢



编辑:我看过这个问题从多列中选择最小值的最佳方式是什么?但不幸的是,由于我正在制作tfs工作项目报告,因为我有义务对此进行规范化处理,因此我无法适应我,而如果我有6个7列。

解决方案

没有内置函数返回两个(或更多)列的最小/最大值。您可以实现自己的标量函数来执行此操作。



在SQL Server 2005+中,您可以使用 UNPIVOT 将列转换成行,然后使用MIN函数:

  CREATE TABLE [X] 

[ID] INT,
[Date1] DATETIME,
[Date2] DATETIME,
[Date3] DATETIME


INSERT [X]
VALUES(0,'09 / 29/2011','09 / 20/2011','09 / 01/2011'),
(1,'01 / 01/2011','01/05/2011','03 / 03/2010')


SELECT [ID],MIN([Date] )AS [MinDate]
FROM [X]
UNPIVOT(
[日期] FOR d IN
([Date1]
,[Date2]
, [Date3])
)unpvt
GROUP BY [ID]


I'm using SQL Server 2008;

Suppose I have a table 'X' with columns 'Date1', 'Date2', 'Dateblah', all of type DateTime.

I want to select the min value between the three columns, for example (simplified, with date mm/dd/yyyy)

ID       Date1          Date2           Dateblah
0     09/29/2011      09/20/2011       09/01/2011 
1     01/01/2011      01/05/2011       03/03/2010

ID    MinDate
0    09/01/2011
1    03/03/2010

Is there a bread and butter command to do that ?

Thanks in advance.

EDIT: I've seen this question What's the best way to select the minimum value from multiple columns? but unfortunately it won't suit me as I'm being obligated to do it against normalization because I'm making tfs work item reports, and the 'brute-force' case thing will end up being a pain if I have 6 ou 7 columns.

解决方案

There is no built in function to return the min/max of two (or more) columns. You could implement your own scalar function to do this.

In SQL Server 2005+ you could use UNPIVOT to turn the columns into rows and then use the MIN function:

CREATE TABLE [X]
(
    [ID] INT,
    [Date1] DATETIME,
    [Date2] DATETIME,
    [Date3] DATETIME
)

INSERT  [X]
VALUES  (0, '09/29/2011', '09/20/2011', '09/01/2011'),
        (1, '01/01/2011', '01/05/2011', '03/03/2010')


SELECT [ID], MIN([Date]) AS [MinDate]
FROM [X]
UNPIVOT (
    [Date] FOR d IN
        ([Date1]
        ,[Date2]
        ,[Date3])
) unpvt
GROUP BY [ID]

这篇关于获取几列之间的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆