SQL查询从同一字段中求和2

时间:2019-02-08 16:11:55

标签: php sql laravel

我正在尝试通过“ created_at”字段的年份获取“类型” = 1且类型= 2的总“金额”。

这是桌子

+-----------------+------------------+------+
| Field           | Type             | Null | 
+-----------------+------------------+------+-----
 | id              | int(10) unsigned | NO   | 

 | type            | int(10) unsigned | YES  |

 | type            | varchar(255)     | NO   | 
| amount          | double(11,2)     | NO   |                           
| created_at      | timestamp        | YES  |
| updated_at      | timestamp        | YES  |   

这是我的代码(仅给出type = 1的总数):

DB::select(
        'SELECT 
                year, 
                created_at,
                type,
                SUM(amount) AS total
          FROM 
              (SELECT 
                YEAR(created_at) AS year, 
                amount, 
                created_at, 
                type 
              FROM table 
              WHERE type= 1) AS t 
          GROUP BY year, type
          ORDER BY year;
    ');

在此先感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您只需要一个简单的查询即可。以日期中的年份为基础,对金额进行总计并按年份和类型分组。仅供参考,您在问题中有两次将type作为字段。这是不可能的,所以我假设第二次确实是其他字段名称。

SELECT
    YEAR(created_at) AS year, 
    type,
    SUM(amount) AS amount
FROM mytable 
GROUP BY YEAR(created_at), type
ORDER BY YEAR(created_at)

DEMO

答案 1 :(得分:0)

我怀疑您真的想要条件聚合:

SELECT YEAR(created_at) AS year, 
       SUM(CASE WHEN type = 1 THEN amount ELSE 0 END) as amount_1,
       SUM(CASE WHEN type = 2 THEN amount ELSE 0 END) as amount_2
FROM table 
GROUP BY YEAR(created_at);

答案 2 :(得分:-1)

您的问题需要进一步澄清,但我认为您想将每年创建的类型1的金额与每年的总金额进行比较。

select year(created_at), created_at, type,
       sum(case when type =1 then amount else 0 end) as type1amount,
       sum(amount) over (partition by year(created_at)) as yeartotal
from table
group by 1,2,3