简体   繁体   English

SQL 为每个属性添加总和行

[英]SQL Add total sum row for each property

I'm trying to create a new total sum row for every state.我正在尝试为每个 state 创建一个新的总和行。

Sample table:样品表:

| State | Item | Amount
    A      X      100
    B      Y      200
    A      Z      100
    B      X      150

Result:结果:

| State | Item | Amount
    A      X      100
    A      Z      100
 Total A          200
    B      Y      200
    B      X      150
 Total B          350

Is there SQL query that I can use to execute that table是否有可用于执行该表的 SQL 查询

Try below query.试试下面的查询。

SELECT * FROM states_YourtableName
    UNION
    SELECT 'Total '+[state] State ,'' Item ,SUM(Amount) Amount
    FROM states_YourtableName GROUP BY [State]

You will get an output as below您将获得如下 output

state   Item    Amount
A        X      100
A        Z      100
B        X      150
B        Y      200
Total A         200
Total B         350

In SQL Server you can use ROLLUP on a GROUP BY clause to get intermediate and overall sums over the grouped by fields.在 SQL 服务器中,您可以在GROUP BY子句上使用ROLLUP来获取按字段分组的中间和总和。 In your case you would group by both state and item to get all rows:在您的情况下,您将按 state 和 item 分组以获取所有行:

SELECT CASE WHEN State IS NULL THEN 'Grand Total'
            WHEN Item IS NULL THEN CONCAT('Total ', State)
            ELSE State
       END AS State,
       Item, 
       SUM(Amount) AS Amount
FROM data
GROUP BY ROLLUP(State, Item)

Output: Output:

State           Item    Amount
A               X       100
A               Z       100
Total A         (null)  200
B               X       150
B               Y       200
Total B         (null)  350
Grand Total     (null)  550

Demo on SQLFiddle SQLFiddle 上的演示

The simplest way would be UNION ALL .最简单的方法是UNION ALL If it suffices to show the state instead of 'Total <state>', this becomes:如果显示 state 而不是“Total <state>”就足够了,则变为:

select state, item, amount from mytable
union all
select state, null, sum(amount) from mytable group by state
order by state, case when item is null then 2 else 1 end, item;

Result:结果:

State | Item | Amount
------+------+-------
    A |    X |    100
    A |    Z |    100
    A |      |    200
    B |    Y |    200
    B |    X |    150
    B |      |    350

SQL is not working as an excel file, it is mostly used to store and process data. SQL 不是 excel 文件,它主要用于存储和处理数据。 If you want to store that data(the Total) in SQL in my opinion the best way to do it is to create another table where you can keep your totals.如果您想将该数据(总计)存储在 SQL 中,我认为最好的方法是创建另一个可以保存总计的表。

If you try just to print the totals in your screen you can check the link https://www.w3schools.com/sql/sql_count_avg_sum.asp如果您只想在屏幕上打印总数,您可以查看链接https://www.w3schools.com/sql/sql_count_avg_sum.asp

You can use group by with Rollup您可以将 group by 与 Rollup 一起使用

Try this -尝试这个 -

declare @Data table
([State] varchar(20), Item varchar(20), Amount int )

Insert into @Data
values
(    'A',      'X',      100),
(    'B',      'Y',      200),
(    'A',      'Z',      100),
(    'B',      'X',      150)

Select [State], Item, Sum(Amount) Amount
From @Data
Group by [State], Item with Rollup

I recommend grouping sets .我推荐grouping sets It provides much more control than rollup :它提供了比rollup更多的控制:

select state, coalesce(item, 'Total') as item,
       sum(amount) as amount
from t
group by grouping sets ( (state, item), (state) );

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

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