mariadb 如何使用SQL对相似选择的值进行聚合和求和?

svujldwt  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(125)

我有一些类似的选择,我想连接和聚合值。我已经尝试了join,inner join,union,union all,没有预期的结果。可以看到选择非常相似。区别是:SUM(comumn_02)*.05 AS SUM_01SUM(comumn_02)*.45 AS SUM_02不同
以及在第二选择中不同于AND COLUMN_05 = BETAAND COLUMN_05 = ALFA
整件事就在这里:

SELECT
    COLUMN_01,
    SUM(COLUMN_02)*.05 AS SUM_01
FROM table
WHERE
    COLUMN_03 = 1
    AND COLUMN_04 = 2
    AND COLUMN_05 = ALFA
GROUP BY COLUMN_01

UNION ALL

SELECT
    COLUMN_01,
    SUM(COLUMN_02)*.45 AS SUM_02
FROM table
WHERE
    COLUMN_03 = 1
    AND COLUMN_04 = 2
    AND COLUMN_05 = BETA
GROUP BY COLUMN_01;

在此示例中,我们得到以下结果:

|-----------|--------|
| COLUMN_01 | SUM_01 |
|-----------|--------|
| value_01  |    465 |
| value_02  |    186 |
| value_03  |    245 |
| value_01  |    102 |
| value_02  |    108 |
| value_03  |    325 |
|--------------------|

但我想要的是:

|-----------|--------|
| COLUMN_01 | SUM_01 |
|-----------|--------|
| value_01  |    567 | //sum of 465 + 102
| value_02  |    294 | //sum of 186 + 108 
| value_03  |    570 | //sum of 245 + 570
|--------------------|

最重要的是,这是可伸缩的吗?也就是说,使用三个或更多的选择“联合”,或者性能会下降很多?

83qze16e

83qze16e1#

查询中的问题是,您在对单个表进行聚合时,使用了UNION ALL来获取值。为了解决问题,您需要颠倒这两个操作的顺序:

  • 首先应用UNION函数
  • 然后使用SUM聚合函数进行聚合
WITH CTE AS(
       SELECT COLUMN_01,
              COLUMN_02*.05 AS COLUMN
       FROM table
       WHERE COLUMN_03 = 1
         AND COLUMN_04 = 2
         AND COLUMN_05 = ALFA

       UNION ALL

       SELECT COLUMN_01,
              COLUMN_02*.45 AS COLUMN
       FROM table
       WHERE COLUMN_03 = 1
         AND COLUMN_04 = 2
         AND COLUMN_05 = BETA
) 
SELECT COLUMN_01,
       SUM(COLUMN) AS SUM_01
FROM CTE
GROUP BY COLUMN_01
daolsyd0

daolsyd02#

使用条件聚合:

SELECT COLUMN_01,
       SUM(COLUMN_02 * CASE COLUMN_05 WHEN 'ALFA' THEN 0.05 WHEN 'BETA' THEN 0.45 END) AS SUM_01
FROM tablename
WHERE COLUMN_03 = 1 AND COLUMN_04 = 2 AND (COLUMN_05 IN ('ALFA', 'BETA'))
GROUP BY COLUMN_01;

相关问题