https://www.cnblogs.com/lyhabc/archive/2015/10/21/4899244.htmlhtml
有時候咱們須要從多個相同的列裏(這些列的數據類型相同)找出最大的那個值,並顯示spa
這裏給出一個例子3d
IF (OBJECT_ID('tempdb..##TestTable') IS NOT NULL) DROP TABLE ##TestTable CREATE TABLE ##TestTable ( ID INT IDENTITY(1,1) PRIMARY KEY, Name NVARCHAR(40), UpdateByApp1Date DATETIME, UpdateByApp2Date DATETIME, UpdateByApp3Date DATETIME ) INSERT INTO ##TestTable(Name, UpdateByApp1Date, UpdateByApp2Date, UpdateByApp3Date ) VALUES('ABC', '2015-08-05','2015-08-04', '2015-08-06'), ('NewCopmany', '2014-07-05','2012-12-09', '2015-08-14'), ('MyCompany', '2015-03-05','2015-01-14', '2015-07-26') SELECT * FROM ##TestTable
結果以下所示code
有三種方法能夠實現htm
方法一blog
SELECT ID , Name , ( SELECT MAX(LastUpdateDate) FROM ( VALUES ( UpdateByApp1Date), ( UpdateByApp2Date), ( UpdateByApp3Date) ) AS UpdateDate ( LastUpdateDate ) ) AS LastUpdateDate FROM ##TestTable
方法二get
SELECT ID , [Name] , MAX(UpdateDate) AS LastUpdateDate FROM ##TestTable UNPIVOT ( UpdateDate FOR DateVal IN ( UpdateByApp1Date, UpdateByApp2Date, UpdateByApp3Date ) ) AS u GROUP BY ID , Name
方法三io
SELECT ID , name , ( SELECT MAX(UpdateDate) AS LastUpdateDate FROM ( SELECT tt.UpdateByApp1Date AS UpdateDate UNION SELECT tt.UpdateByApp2Date UNION SELECT tt.UpdateByApp3Date ) ud ) LastUpdateDate FROM ##TestTable tt
第一種方法使用values子句,將每行數據構造爲只有一個字段的表,之後求最大值,很是巧妙ast
第二種方法使用行轉列常常用的UNPIVOT 關鍵字進行轉換再顯示class
第三種方法跟第一種方法差很少,可是使用union將三個UpdateByAppDate字段合併爲只有一個字段的結果集而後求最大值
第一種方法的執行計劃
第二種方法的執行計劃
第三種方法的執行計劃
總的來講,第一種方法的執行計劃是最好的
注意,這裏不涉及分組
IF (OBJECT_ID('tempdb..##TestTable') IS NOT NULL) DROP TABLE ##TestTable CREATE TABLE ##TestTable ( ID INT IDENTITY(1, 1) PRIMARY KEY , Name NVARCHAR(40) , UpdateByApp1Date DATETIME , UpdateByApp2Date DATETIME , UpdateByApp3Date DATETIME ) INSERT INTO ##TestTable ( Name, UpdateByApp1Date, UpdateByApp2Date, UpdateByApp3Date ) VALUES ( 'ABC', '2015-08-05', '2015-08-04', '2015-08-06' ), ( 'ABC', '2015-07-05', '2015-06-04', '2015-09-06' ), ( 'NewCopmany', '2014-07-05', '2012-12-09', '2015-08-14' ), ( 'MyCompany', '2015-03-05', '2015-01-14', '2015-07-26' ) SELECT * FROM ##TestTable SELECT ID , Name , ( SELECT MAX(LastUpdateDate) FROM ( VALUES ( UpdateByApp1Date), ( UpdateByApp2Date), ( UpdateByApp3Date) ) AS UpdateDate ( LastUpdateDate ) ) AS LastUpdateDate FROM ##TestTable
name列相同的話,是沒法得出name分組以後的最大值,這裏要注意一下