使SQL Server数据库"view"仅显示具有最大特定列的列的重复行



因此,例如,我在数据库中有一个带有这5行的表:

Test1 ‌ ‌ ‌ C1 ‌ ‌ ‌ 143 ‌ ‌ ‌ 1
Test1 ‌ ‌ ‌ C1 ‌ ‌ ‌ 110 ‌ ‌ ‌ 3
Test2 ‌ ‌ ‌ C2 ‌ ‌ ‌ 923 ‌ ‌ ‌ 6
Test2 ‌ ‌ ‌ C2 ‌ ‌ ‌ 123 ‌ ‌ ‌ 9
Test2 ‌ ‌ ‌ C2 ‌ ‌ ‌ 332 ‌ ‌ ‌ 3

我希望一个视图忽略第三列,并基于第1列和第2列收集相似的行,并根据第四列省略了较低的行,以获取这样的结果:

Test1 ‌ ‌ ‌ C1 ‌ ‌ ‌ 110 ‌ ‌ ‌ 3
Test2 ‌ ‌ ‌ C2 ‌ ‌ ‌ 123 ‌ ‌ ‌ 9

SQL Server的数据库视图是否可以?

相当标准的解决方案是使用聚合和JOIN

select dat.*
from dat
join
(
    select c1, c2, max(c4) max_c4
    from dat
    group by c1, c2
) t on dat.c1 = t.c1 and
    dat.c2 = t.c2 and 
    dat.c4 = t.max_c4

dbfiddle demo

另一个解决方案是使用窗口函数,但是,在某些情况下,它可能不必要。

您可以使用col1,col2的Min(Col4(组的子查询,并使用内部加入获取所有列值相关

select * from my_table m 
inner join ( 
select col1, col2,  min(col4)
my_table
group by col1, col2 ) t on m.col1 = t.col1 and m.col2= t.col2

使用子字符串并生成演示数据:

WITH mydata(a,b,c,d) as 
 (
 select * from 
 (
 VALUES ('teste1','c1',143,1),
  ('teste1','c1',110,3),
  ('teste2','c2',923,6),
  ('teste2','c2',123,9),
  ('teste2','c2',332,3)
 ) as x(a, b , d, e)
 )
select distinct a,b,(select top 1 max(d) from mydata d1 where d1.a= d2.a and d1.b = d2.b) from mydata d2 

SQL Server的版本是否支持Row_number函数?

WITH
  v AS (
    SELECT *,
      ROW_NUMBER()
        OVER(PARTITION BY a ORDER BY e DESC) n
    FROM(
      VALUES('teste1', 'c1', 143, 1),
            ('teste1', 'c1', 110, 3),
            ('teste2', 'c2', 923, 6),
            ('teste2', 'c2', 123, 9),
            ('teste2', 'c2', 332, 3)
    ) t(a, b, d, e)
  )
SELECT a, b, d, e
FROM v
WHERE n = 1;

在Rextester.com上检查它

最新更新