简体   繁体   English

如何在 MS SQL Server 表上进行选择以在一行中显示其某些列数据并使用 sum 函数

[英]How make a select on a MS SQL Server table to show some of its column data in a row and use sum function

I have a MS SQL Server table as below:我有一个 MS SQL Server 表,如下所示:

在此处输入图片说明

and I need to change it into below format with TSQL:我需要使用 TSQL 将其更改为以下格式:

在此处输入图片说明

How can I do this?我怎样才能做到这一点? Any help will be appriciated!任何帮助都会得到帮助!

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.

相关问题 如何在MS SQL Server中为表的每一行创建一个选择? - How to create a select for each row of table in ms sql server? 如何选择数据库SQL Server中的最后8行并将其他列求和 - how to select the last 8 row and Sum other column in Database SQL Server 如何对数据库表中记录的两个单元格进行聚合函数,并在 MS SQL Server 中的另一个表中显示其结果 - How do aggregate function on two cells of a record in a database table and show its result in another table in MS SQL Server 使用MS SQL Server函数作为列别名 - Use an MS SQL Server function as a column alias SQL Server +选择行及其子表内容 - SQL Server + select row and its sub table contents SQL Server:如何在列中选择具有相同值的行,但在另一列上为分组行选择一些精确值 - SQL Server : how to select the rows in a table with the same value on a column but some exact values on another column for the grouped rows 如何根据SQL Server中行的列值从表中选择行 - How can i select row from table according to column values of row in sql server 如何在SQL Server中创建一个接受数据列的函数? - How do I make a function in SQL Server that accepts a column of data? MS SQL使一个表的列依赖于其他表值的总和 - MS SQL Make a column of one table depend on other table values sum 如何使用sql查询仅选择表底部的客户数据和总和作为行? - How to select only customer data and sum of that at bottom of table as row using sql query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM