0

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

例子:

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

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

4

2 回答 2

3

你可以使用group by

select  DATADATE
,       max(IDs)
from    YourTable
group by
        DATADATE
于 2012-05-08T06:31:59.370 回答
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
于 2012-05-08T06:44:09.690 回答