gpt4 book ai didi

带分组依据的 MySQL 案例

转载 作者:行者123 更新时间:2023-11-29 01:55:51 30 4
gpt4 key购买 nike

我有一个像这样的表(name=expense):

id  amount  date
1 -1687 2014-01-02 00:00:00.0
2 11000 2014-01-02 00:00:00.0
3 1500 2014-01-03 00:00:00.0
4 -3800 2014-01-03 00:00:00.0
5 119500 2014-01-01 00:00:00.0
6 -2999 2014-01-04 00:00:00.0
7 5972 2014-01-04 00:00:00.0
..
8 7208 2014-12-31 00:00:00.0

我能够检索收入并按月分组,如下所示:

SELECT 
SUM(amount),
date
FROM expense
WHERE YEAR(now()) = YEAR(date) AND amount>0
GROUP BY MONTH(date);

我能够检索费用并按月分组,如下所示:

SELECT
SUM(amount),
date
FROM expense
WHERE YEAR(now()) = YEAR(date) AND amount<=0
GROUP BY MONTH(date);

我想知道是否有一种方法可以组合这两个查询并检索incomeexpense 并在单个查询<中按月分组/em>.

最佳答案

是的,您需要一个 Case 语句:

SELECT
sum(case when amount> 0 then amount end) as income,
sum(case when amount<=0 then amount end) as expense,
date
FROM expense
WHERE YEAR(now()) = YEAR(date)
GROUP BY MONTH(date);

关于带分组依据的 MySQL 案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29553709/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com