SQL Server,按分组,汇总为单个结果

时间:2019-03-25 16:22:01

标签: sql sql-server

我有一个SQL查询,该查询将数据返回到多个记录(前4个记录)中。

enter image description here

如何将以上4行合并为一个记录结果?

类型为空的产品只有V1,V1_Status,V2和V2_Status

在我的查询中,我已经这样做了:

SELECT Product, Max(Type), Max(V1), Max(V1_Status), Max(V2), Max(V2_Status), Max(V3), Max(V3_Status), Max(V4), Max(V4_Status), Max(V5), Max(V5_Status)
FROM Table 
WHERE condition
GROUP BY Product, Type

2 个答案:

答案 0 :(得分:2)

您不需要GROUP BY Type,即

SELECT Product, 
Max(V1), 
Max(V1_Status), 
Max(V2), 
Max(V2_Status), 
Max(V3), 
Max(V3_Status), 
Max(V4), 
Max(V4_Status), 
Max(V5), 
Max(V5_Status)
FROM Table 
WHERE condition
GROUP BY Product

答案 1 :(得分:0)

使用row_number()

select * from    
(
select t.*,row_number()over(partition by product order by v1 desc) rn
from table_name t
) a where a.rn=1