Oracle中的SUM多列值

时间:2017-04-25 18:24:02

标签: sql oracle sum

我不是Oracle的专家。 我在Oracle 11 G DB上有下表'Fruits':

Fruits:
DateTime    Fruit   Raw Rotten  Ripe
18-Jan-17   Banana  5   3   1
19-Feb-17   Banana  4   3   2
19-Jan-17   Banana  0   1   0
20-Feb-17   Banana  8   9   21
18-Jan-17   Apple   5   3   1
19-Feb-17   Apple   4   3   2
19-Jan-17   Apple   0   1   0
20-Feb-17   Apple   8   9   21
18-Jan-17   Mango   5   3   1
19-Feb-17   Mango   4   3   2
19-Jan-17   Mango   0   1   0
20-Feb-17   Mango   8   9   21
18-Jan-17   Guava   5   3   1
19-Feb-17   Guava   4   3   2
19-Jan-17   Guava   0   1   0
20-Feb-17   Guava   8   9   21

我想写一个查询给我以下输出: 期望的输出:

DTM     Fruit   Total(Raw)  Total(Rotten)   Total(Ripe)
Jan-17  Banana      5           4               1
Jan-17  Apple       5           4               1
Jan-17  Mango       5           4               1
Jan-17  Guava       5           4               1
Feb-17  Banana      12          12              23
Feb-17  Apple       12          12              23
Feb-17  Mango       12          12              23
Feb-17  Guava       12          12              23

我一直试图找到一些与我的情况相关的例子,但没有到达那里。请指导我解决这个问题。

3 个答案:

答案 0 :(得分:0)

这是一个简单的小组

SELECT EXTRACT(MONTH FROM DateTime), 
       EXTRACT(YEAR FROM DateTime), 
       Fruit,
       SUM(RAW) as T_RAW, 
       SUM(ROTTON) AS T_ROTTEN, 
       SUM(RIPE) as T_RIPE
FROM TABLE_NAME_YOU_DID_NOT_SAY
GROUP BY EXTRACT(MONTH FRM DateTime), EXTRACT(YEAR FROM DateTime), Fruit

nb - 之前我在SQL SERVER中展示了如何做到这一点:

SELECT MONTH(DateTime), YEAR(DateTime), Fruit, SUM(RAW) as T_RAW, SUM(ROTTON) AS T_ROTTEN, SUM(RIPE) as T_RIPE
FROM TABLE_NAME_YOU_DID_NOT_SAY
GROUP BY MONTH(DateTime), YEAR(DateTime), Fruit

答案 1 :(得分:0)

您需要使用TRUNC( datetime, 'MM' )DateTime值截断到月初,然后将其包含在GROUP BY语句中:

SELECT TRUNC( DateTime, 'MM' ),
       Fruit,
       SUM( raw )    AS "Total(Raw)",
       SUM( rotten ) AS "Total(Rotten)",
       SUM( ripe)    AS "Total(Ripe)"
FROM   your_table
GROUP BY TRUNC( DateTime, 'MM' ), Fruit

或者您可以将DateTime转换为字符串:

SELECT TO_CHAR( DateTime, 'Mon-YY' ),
       Fruit,
       SUM( raw )    AS "Total(Raw)",
       SUM( rotten ) AS "Total(Rotten)",
       SUM( ripe)    AS "Total(Ripe)"
FROM   your_table
GROUP BY TO_CHAR( DateTime, 'Mon-YY' ), Fruit

答案 2 :(得分:-1)

SELECT EXTRACT(MONTH FROM DateTime), 
       EXTRACT(YEAR FROM DateTime), 
       Fruit, 
       SUM(RAW) as Total_raw,
       SUM(ROTTEN) AS Total_rotten,
       SUM(RIPE) as Total_ripe
 FROM YOURTABLE
GROUP BY MONTH(DateTime), 
         YEAR(DateTime),
         Fruit;