SQL:从列显示不同的记录

时间:2013-07-30 05:52:38

标签: sql sql-server sql-server-2008

示例数据:

LogID     OrderNo     MaxDate              AnotherDate     Status
NULL      1           2013-07-30 12:01:00  NULL            Pending
NULL      1           2013-07-30 12:01:01  NULL            Pending
NULL      1           2013-07-30 12:01:02  NULL            Pending
NULL      2           2013-07-30 12:02:00  NULL            Pending
NULL      3           2013-08-01 12:30:00  NULL            Pending

预期产出:

LogID     OrderNo     MaxDate     AnotherDate     Status
NULL      1           2013-07-30  NULL            Pending
NULL      2           2013-07-30  NULL            Pending
NULL      3           2013-08-30  NULL            Pending

LogID OrderNo 都是外键。 MaxDate 的数据类型为日期时间

更新

尝试使用此SQL语句:

SELECT DISTINCT(OrderNo), LogID, MaxDate, AnotherDate, Status
FROM Logs

但仍显示3号订单

4 个答案:

答案 0 :(得分:5)

我认为select distinct * from <your table>适合您

在不同时间的情况下,您可以使用:

 select distinct 
     LogID,
     OrderNo,
     cast(MaxDate as date) as MaxDate,
     AnotherDate,
     Status
 from <your table>

答案 1 :(得分:2)

   Select LogId,
           OrderNo,
          Cast( MaxdATE as Date) as MaxdATE  ,
           AnotherDate,
           Status from
    (
            Select LogId,
            OrderNo,
            MaxdATE,
            AnotherDate,
            Status,
           Row_Number() Over( Partition by OrderNo Order by MaxDate Desc) as Row
            from TableName
    ) T where T.Row=1

答案 2 :(得分:2)

我认为你所寻找的是这样的:

SELECT [LOGID], 
       [ORDERNO], 
       Max([MAXDATE]) MaxDate, 
       [ANOTHERDATE], 
       [STATUS] 
FROM   Logs
GROUP  BY [LOGID], 
          [ORDERNO], 
          [ANOTHERDATE], 
          [STATUS] 

看一下这个SQL Fiddle的例子。

答案 3 :(得分:1)

我认为这足以满足您的要求

SELECT DISTINCT 
       LogID ,
       OrderNo,
       MaxDate ,
       AnotherDate,
       Status
FROM table

或者如果你想根据你的外键取得不同,你可以使用这个

;WITH cte AS
(
   SELECT
     ROW_NUMBER() OVER (PARTITION BY LogID ,OrderNo ORDER BY MaxDate ) AS rno,
      LogID ,
           OrderNo,
           MaxDate ,
           AnotherDate,
           Status
    FROM table
 )
SELECT * FROM cte WHERE rno =1