将其他列(时间)添加到DISTINCT行

时间:2014-08-13 11:06:29

标签: sql-server distinct

我选择

的唯一行
SELECT DISTINCT 
    LogContent
FROM   
    [WebAppLog] WITH (NOLOCK)
WHERE  
    LogName = 'frontendErrorLog'

但如何将结果与其他列配对?我想选择唯一的LogName并将其分配给最早的LogTime,就像在:

SELECT 
    LogTime, LogContent 
FROM   
    [WebAppLog] WITH (NOLOCK) 
WHERE  
    LogName = 'frontendErrorLog'

2 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER

WITH CTE AS
(
    SELECT LogTime, LogContent, 
           rn = ROW_NUMBER() OVER (PARTITION BY LogContent ORDER BY LogTime ASC)
    FROM [WebAppLog] WITH (NOLOCK) 
    WHERE LogName = 'frontendErrorLog'
)
SELECT LogTime, LogContent FROM CTE WHERE rn = 1

答案 1 :(得分:0)

@Ultra

分组是否适合您,就像这样。

SELECT  LogContent,MAX(LogTime) LogTime
FROM    [WebAppLog] WITH (NOLOCK) 
WHERE   LogName = 'frontendErrorLog'
GROUP   BY LogContent