使 SQL 服务器数据库 "view" 只显示具有最大特定列的列的重复行
Make SQL Server database "view" only show the duplicate rows which has column with the biggest specific column
例如,我有一个 table,数据库中有这 5 行:
Test1 C1 143 1
Test1 C1 110 3
Test2 C2 923 6
Test2 C2 123 9
Test2 C2 332 3
我想要一个忽略第三列的视图,并根据第 1 列和第 2 列收集相似的行,并根据第 4 列忽略较低值的行,以获得如下结果:
Test1 C1 110 3
Test2 C2 123 9
SQL 服务器的数据库视图是否可行?
您可以使用 min(col4) group by col1, col2 的子查询,并使用 inner join 获取所有相关的列值
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
非常标准的解决方案是使用聚合和 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
另一种解决方案是使用 window 函数,但是,在 中它可能不必要地慢。
您的SQL服务器版本是否支持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;
上查看
例如,我有一个 table,数据库中有这 5 行:
Test1 C1 143 1
Test1 C1 110 3
Test2 C2 923 6
Test2 C2 123 9
Test2 C2 332 3
我想要一个忽略第三列的视图,并根据第 1 列和第 2 列收集相似的行,并根据第 4 列忽略较低值的行,以获得如下结果:
Test1 C1 110 3
Test2 C2 123 9
SQL 服务器的数据库视图是否可行?
您可以使用 min(col4) group by col1, col2 的子查询,并使用 inner join 获取所有相关的列值
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
非常标准的解决方案是使用聚合和 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
另一种解决方案是使用 window 函数,但是,在
您的SQL服务器版本是否支持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;
上查看