SQL中不同datadate的不同值

时间:2012-05-08 06:29:54

标签: sql sql-server date sql-server-2008-r2 distinct

在我的表中,我有时会有两个带有两个值的日期,但我只需要其中一个。无论如何根据不同的日期选择一个不同的值?

示例:

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

我需要得到的是:

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

非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用group by

select  DATADATE
,       max(IDs)
from    YourTable
group by
        DATADATE

答案 1 :(得分:0)

如果您使用的是sql server 2005+。然后你可以这样做:

;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

修改

在CTE功能中,您可以join或执行您无法获得所需输出的功能。像这样:

;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