[英]How make a select on a MS SQL Server table to show some of its column data in a row and use sum function
You can do conditional aggregation:您可以进行条件聚合:
select
title,
max(case when [type] = 'type1' then [number] end) [type1],
max(case when [type] = 'type2' then [number] end) [type2]
from mytable
group by title
If you may possibly have more than one record for a given (title, type)
tuple, you might want to use another aggregate function than max()
, like sum()
or avg()
.如果给定
(title, type)
元组可能有多个记录,则可能需要使用除max()
之外的另一个聚合函数,例如sum()
或avg()
。
Sounds like you want a PIVOT ...听起来你想要一个 PIVOT ......
SELECT title,
[type1] AS type1,
[type2] AS type2
FROM
(SELECT title, [type], [number])
AS Source
PIVOT
(
sum([number])
FOR
[[type]]
IN ( [type1], [type2])
) AS PVT;
https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15 https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.