CREATE TABLE #TABLE(
category_id INT
,data_value FLOAT
)
INSERT INTO #TABLE(category_id,data_value)Values(1,174.2583)
INSERT INTO #TABLE(category_id,data_value)Values(2,1537.2326)
INSERT INTO #TABLE(category_id,data_value)Values(3,141.1724)
INSERT INTO #TABLE(category_id,data_value)Values(4,35.3124)
/*方法1*/
SELECT
SUM(data_value) AS GROUP_A
FROM #TABLE
WHERE (category_id=1 OR category_id=2 )
SELECT
SUM(data_value) AS GROUP_A
FROM #TABLE
WHERE (category_id=3 OR category_id=4 )
/*方法2*/
SELECT
(
SELECT
SUM(data_value) AS GROUP_A
FROM #TABLE
WHERE (category_id=1 OR category_id=2 )
) GROUP_A
,
(
SELECT
SUM(data_value) AS GROUP_B
FROM #TABLE
WHERE (category_id=3 OR category_id=4 )
) GROUP_B
DROP TABLE #TABLE
先假設你要每兩個相加
SELECT (category_id-1)/2,SUM(data_value)
FROM t
GROUP BY (category_id-1)/2
你可以使用 GROUP BY 來將相同的 category_id 分組,然後使用聚合函數 SUM 加總對應的 data_value。
下面是一個範例 SQL 語句:
SELECT
SUM(CASE WHEN category_id IN (1, 2) THEN data_value ELSE 0 END) AS sum_1_2,
SUM(CASE WHEN category_id IN (3, 4) THEN data_value ELSE 0 END) AS sum_3_4
FROM your_table;