SQL Server:为每列选择不同的值

时间:2017-01-09 10:22:31

标签: sql-server tsql

如果可以过滤选择结果,删除部分重叠的值

,我就会徘徊

例如下面,我有成千上万的记录,但是我需要'周日'值是unqiue,如果是重复,那么值最高的那个应该保留。

emplo   project_id  Value   week_Date    week_ActualStart   week_ActualEnd
A0001   project001  100     2015-12-28   2015-12-28         2016-01-03 
A0001   project001  60      2015-12-28   2016-01-01         2016-01-03 

所以只剩下第一行。

我真的可以使用别人的建议

2 个答案:

答案 0 :(得分:1)

尝试以下内容:

;WITH WeekDateCte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY emplno, week_Date ORDER BY Value DESC) RowNo 
    FROM employee
)
SELECT * 
FROM WeekDateCte 
WHERE RowNo = 1

有关ROW_NUMBER函数的详细信息,请查看here

注意: ROW_NUMBER()会返回BIGINT

答案 1 :(得分:0)

您可以使用ROW_NUMBER

SELECT emplno, project_id, Value, week_Date,
       week_ActualStart, week_ActualEnd
FROM (
   SELECT emplno, project_id, Value, week_Date,
          week_ActualStart, week_ActualEnd,
          ROW_NUMBER() OVER (PARTITION BY emplno, week_Date 
                             ORDER BY Value DESC) AS rn
   FROM mytable) AS t
WHERE t.rn = 1

查询选择每个Value切片具有最大emplno, week_Date的行。