You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数据表中求和值的总和计算:SQL实现需求问询

Fixing Your SQL Calculation for Total Sum of (item_1 + item_2)

Let's break down what's going wrong with your current query first:
Your existing code select *,(item 1 + item 2 ) + (item 1 + item 2 ) as ItemS from MyTable is calculating twice the sum of item_1 and item_2 for each individual row (so the first row would return 4, the second 6), not the total sum across all rows.

To get the total sum of item_1 + item_2 (which is 5 in your case) as you want, here are two common approaches depending on your desired output format:

Option 1: Show Total Sum on Every Row

If you want the total sum displayed alongside each row of original data, use a window function (supported in most modern databases like PostgreSQL, MySQL 8+, SQL Server, etc.):

SELECT 
    item_1,
    item_2,
    item_3,
    item_4,
    SUM(item_1 + item_2) OVER () AS ItemS
FROM MyTable;

This query calculates the global sum of item_1 + item_2 across all rows and repeats it in every row's ItemS column.

Option 2: Show Total Sum as a Separate Final Row

If you want the original rows first, followed by a single row with the total sum (matching your expected output), use UNION ALL to combine your original data with an aggregate sum query:

-- Fetch original rows with empty ItemS column
SELECT 
    item_1,
    item_2,
    item_3,
    item_4,
    NULL AS ItemS
FROM MyTable

UNION ALL

-- Calculate total sum, leave other columns empty
SELECT 
    NULL,
    NULL,
    NULL,
    NULL,
    SUM(item_1 + item_2) AS ItemS
FROM MyTable;

Note: If you prefer empty strings instead of NULL in the first part's ItemS column, replace NULL with '' (works in most databases; adjust if using a niche system).

For Older Databases Without Window Functions

If you're using an older database that doesn't support window functions (e.g., MySQL 5.x), use a subquery to fetch the total sum:

SELECT 
    item_1,
    item_2,
    item_3,
    item_4,
    (SELECT SUM(item_1 + item_2) FROM MyTable) AS ItemS
FROM MyTable;

This achieves the same result as Option 1, just using a subquery instead of a window function.

内容的提问来源于stack exchange,提问作者karan sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:43:37