0

In my table I sometimes have two dates with two values, but I just need one of them. Is there anyway to select a distinct value based on the distinct date?

example:

DATADATE                ID
2008-06-30 00:00:00.000 12
2008-03-31 00:00:00.000 12
2007-12-31 00:00:00.000 3
2007-12-31 00:00:00.000 12
2007-09-30 00:00:00.000 3
2007-09-30 00:00:00.000 12
2007-06-30 00:00:00.000 3
2007-06-30 00:00:00.000 12
2007-03-31 00:00:00.000 3
2007-03-31 00:00:00.000 12
2006-12-31 00:00:00.000 3
2006-09-30 00:00:00.000 3
2006-06-30 00:00:00.000 3

What I need to get is this:

DATADATE                ID
2008-06-30 00:00:00.000 12
2008-03-31 00:00:00.000 12
2007-12-31 00:00:00.000 12
2007-09-30 00:00:00.000 12
2007-06-30 00:00:00.000 12
2007-03-31 00:00:00.000 12
2006-12-31 00:00:00.000 3
2006-09-30 00:00:00.000 3
2006-06-30 00:00:00.000 3

Any help is really appreciated, thanks.

1
  • What version of sql-server are you using?
    – Arion
    May 8, 2012 at 6:44

2 Answers 2

3

You could use group by:

select  DATADATE
,       max(IDs)
from    YourTable
group by
        DATADATE
2
  • I am using SQL Server 2008 R2 May 8, 2012 at 7:36
  • basically, if there are two datadate values that just choose one of them May 8, 2012 at 7:44
0

If you are using sql server 2005+. Then you can do this:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY ID ORDER BY DATADATE DESC) AS RowNbr,
        Table1.*
    FROM
        Table1
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.RowNbr=1

EDIT

In the CTE function you can join or do what ever you cant to get the output you want. Like this:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY Table1.ID ORDER BY Table2.DATADATE DESC) AS RowNbr,
        Table1.*
    FROM
        Table1
        JOIN Table2
            ON Table1.ID = Table2.ID
)
SELECT
    *
FROM
    CTE

WHERE
    CTE.RowNbr=1
1
  • The problem is that there is more than one table.. the above date distinct and corresponding value distinct apply for just one table, while there are other tables in the query but they don't need to be modified the value the row that is excepted for the date is fine May 8, 2012 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.