简体   繁体   English

T-SQL汇总

[英]T-SQL Summation

I'm trying to create result set with 3 columns. 我正在尝试创建3列的结果集。 Each column coming from the summation of 1 Column of Table A but grouped by different ID's. 每列来自表A的1列的总和,但按不同的ID分组。 Here's an overview of what I wanted to do.. 这是我想做的概述。

Table A
ID       Val.1      
1          4
1          5
1          6
2          7
2          8
2          9
3         10
3         11   
3         12

I wanted to create something like.. 我想创建类似..

ROW       SUM.VAL.1          SUM.VAL.2         SUM.VAL.3
1            15                 21                33

I understand that I can not get this using UNION, I was thinking of using CTE but not quite sure with the logic. 我知道我无法使用UNION来获得此功能,我当时正在考虑使用CTE,但逻辑上不太确定。

You need conditional Aggregation 您需要条件聚合

select 1 as Row,
       sum(case when ID = 1 then Val.1 end),
       sum(case when ID = 2 then Val.1 end),
       sum(case when ID = 3 then Val.1 end)
From yourtable 

You may need dynamic cross tab or pivot if number of ID's are not static 如果ID's数量不是静态ID's则可能需要动态交叉表或数据透视表

DECLARE @col_list VARCHAR(8000)= Stuff((SELECT ',sum(case when ID = '+ Cast(ID AS VARCHAR(20))+ ' then [Val.1] end) as [val.'+Cast(ID AS VARCHAR(20))+']'
                    FROM   Yourtable
                    GROUP  BY ID
                    FOR xml path('')), 1, 1, ''),
        @sql      VARCHAR(8000) 

exec('select 1 as Row,'+@col_list +'from Yourtable')

I think pivoting the data table will yield the desired result. 我认为透视数据表将产生期望的结果。

IF OBJECT_ID('tempdb..#TableA') IS NOT NULL
    DROP TABLE #TableA

CREATE TABLE #TableA
(
    RowNumber INT, 
    ID INT,
    Value INT
)
INSERT #TableA VALUES (1, 1, 4)
INSERT #TableA VALUES (1, 1, 5)
INSERT #TableA VALUES (1, 1, 6)
INSERT #TableA VALUES (1, 2, 7)
INSERT #TableA VALUES (1, 2, 8)
INSERT #TableA VALUES (1, 2, 9)
INSERT #TableA VALUES (1, 3, 10)
INSERT #TableA VALUES (1, 3, 11)
INSERT #TableA VALUES (1, 3, 12)

-- https://msdn.microsoft.com/en-us/library/ms177410.aspx

SELECT RowNumber, [1] AS Sum1, [2] AS Sum2, [3] AS Sum3
FROM 
(
    SELECT RowNumber, ID, Value 
    FROM #TableA
) a
PIVOT
(
    SUM(Value)
    FOR ID IN ([1], [2], [3])
) AS p

This technique works if the ids you are seeking are constant, otherwise I imagine some dyanmic-sql would work as well if changing ids are needed. 如果您要查找的ID是恒定的,则此技术有效,否则我想如果需要更改ID,则某些dyanmic-sql也可以工作。

https://msdn.microsoft.com/en-us/library/ms177410.aspx https://msdn.microsoft.com/zh-CN/library/ms177410.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM