如何在SQL查询中仅包含单个(第一个)重复行

时间:2017-11-24 21:05:06

标签: sql sql-server tsql

我的问题是收入字段,其中值已重复三次。我需要一个select查询,它排除了两个重复值,但保留了一行。查询还必须包含非重复行。

timeStamp             fieldValue          prevValue     newValue
17/11/2017 11:41      Revenue             £0.00         £12,000.00
17/11/2017 11:41      Revenue             £0.00         £12,000.00
17/11/2017 11:41      Revenue             £0.00         £12,000.00
17/11/2017 11:42      Revenue             £0.00         £16,000.00
17/11/2017 11:42      Revenue             £0.00         £16,000.00
17/11/2017 11:42      Revenue             £0.00         £16,000.00
17/11/2017 11:42      Revenue             £16,000.00      £18,000.00
17/11/2017 11:42      Revenue             £18,000.00      £16,000.00
17/11/2017 11:42      Status              Open          Won
17/11/2017 11:42      Est. Close Date     24/11/2017      21/12/2017
17/11/2017 18:17      Est. Close Date     19/01/2018      16/02/2018
17/11/2017 18:17      Revenue             £16,000.00      £18,000.00
17/11/2017 18:18      Revenue             £18,000.00      £16,000.00
17/11/2017 18:18      Status              Open          Won
17/11/2017 14:35      Est. Close Date     24/11/2017      21/12/2017
20/11/2017 10:26      Est. Close Date     19/01/2018      16/02/2018

完全坚持这一点,任何指导都将非常感谢。使用SQL Server 2014。

3 个答案:

答案 0 :(得分:0)

import spam as sp

答案 1 :(得分:0)

您可以使用子查询来实现此目的

SELECT timeStamp, fieldValue,prevValue,newValue FROM 
    (SELECT timeStamp, fieldValue,prevValue,newValue,
            ROW_NUMBER() OVER (Partition BY timeStamp, fieldValue, prevValue, 
            newValue ORDER BY timestamp) as rownum ) AS T1
WHERE T1.rownum = 1

答案 2 :(得分:0)

;WITH CTE
AS
(
SELECT timeStamp,
       fieldValue,
       prevValue,
       newValue,
       ROW_NUMBER() OVER(PARTITION BY timeStamp, fieldValue, prevValue, newValue ORDER BY timeStamp) AS RowNumb
    FROM TableName
    WHERE fieldValue = 'Revenue'
)
SELECT timeStamp,
       fieldValue,
       prevValue,
       newValue
    FROM CTE 
    WHERE RowNumb = 1
UNION
SELECT timeStamp,
       fieldValue,
       prevValue,
       newValue
    FROM TableName
    WHERE fieldValue != 'Revenue'