Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
hi want to retrieve max date from multiple column
say
i have column



a1|a2|a3|a4|b1|b2|b3|b4

all these are column now what i want is i want to get the latest date
from a1|a2|a3|a4

and |b1|b2|b3|b4 there ar more columns c1......,d1,e1.........so sone just for the sake of simplicity
i have mention two series
so far i have written
SQL
Select 
   
  MAX(HepatitisBDate.im_HepatitisBDate1)  as 'iHepatitisBDate1'

   from
   ( 
Select CONVERT(DATE,ISNULL(im_HepatitisBDate1 , CONVERT(DATE,'01/01/1800',103)),103)as im_HepatitisBDate1 from md_Immunization 
Union 
Select CONVERT(DATE,ISNULL(im_HepatitisBDate2 , CONVERT(DATE,'01/01/1800',103)),103)as im_HepatitisBDate1 from md_Immunization 
Union 
Select CONVERT(DATE,ISNULL(im_HepatitisBDate3 , CONVERT(DATE,'01/01/1800',103)),103)as im_HepatitisBDate1 from md_Immunization 
Union 
Select CONVERT(DATE,ISNULL(im_HepatitisBDate4 , CONVERT(DATE,'01/01/1800',103)),103)as im_HepatitisBDate1 from md_Immunization 
) as HepatitisBDate
Posted
Updated 23-Sep-13 20:29pm
v2

Solution 1 (using TOP, MAX[^] and UNPIVOT[^])
SQL
SELECT TOP(1) FieldName, MAX(DateValue) AS MaxDate
FROM (
    SELECT FieldName, DateValue
    FROM (
        SELECT a1, a2, a3, a4, b1, b2, b3, b4
        FROM TableName
        ) AS pvt
    UNPIVOT (DateValue FOR FieldName IN(a1, a2, a3, a4, b1, b2, b3, b4)) AS unpvt
    ) AS T
GROUP BY FieldName
ORDER BY DateValue DESC


Solution 2 (using RANK[^] and UNPIVOT[^])
SQL
--DROP TABLE #Integers

CREATE TABLE #Integers (a1 INT, a2 INT, a3 INT, a4 INT,
                        b1 INT, b2 INT, b3 INT, b4 INT,
                        c1 INT, c2 INT, c3 INT, c4 INT)

INSERT INTO #Integers (a1, a2, a3, a4,
                        b1, b2, b3, b4,
                        c1, c2, c3, c4)
SELECT 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
UNION ALL SELECT 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
UNION ALL SELECT 8, 5, 2, 7, 4, 1, 9, 6, 3, 1, 2, 3
UNION ALL SELECT 3, 6, 9, 1, 4, 7, 2, 5, 8, 9, 8, 7

SELECT FieldName, FieldValue
FROM (
    SELECT FieldName, FieldValue, RANK() OVER(ORDER BY FieldValue DESC) AS [Rank]
    FROM (
        SELECT *
        FROM #Integers
    ) AS pvt
    UNPIVOT (FieldValue FOR FieldName IN(a1, a2, a3, a4,
                                        b1, b2, b3, b4,
                                        c1, c2, c3, c4)) AS unpvt
) AS T
WHERE [Rank]=1

DROP TABLE #Integers
 
Share this answer
 
v2
Comments
gvprabu 24-Sep-13 8:47am    
Very nice example.... my 5+ :-)
Maciej Los 24-Sep-13 8:48am    
Thank you, Gopal.
But where is a 5? ;)
I think this can solve your problem
http://stackoverflow.com/a/1398019/599560[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900