根据日期分组获取数据

时间:2018-10-04 12:31:19

标签: php mysql sql mysqli

这是我的桌子

enter image description here

其中的字段类型表示1代表收入,2代表支出

例如,现在表中的要求是在2-10-2018上进行了两次交易,因此我需要以下数据

Expected Output

id   created_date   total_amount
1       1-10-18     10
2       2-10-18     20(It calculates all only income transaction made on 2nd date)
3       3-10-18     10
and so on...

它将返回一个新字段,其中仅包含在死皮日进行的incom交易

我尝试过的是

 SELECT * FROM `transaction`WHERE type = 1 ORDER BY created_date ASC
 UNION
 SELECT()


//But it wont work
SELECT created_date,amount,status FROM
    (
        SELECT COUNT(amount) AS totalTrans FROM transaction WHERE created_date = created_date
    ) x
 transaction

您还可以在此处看到架构 http://sqlfiddle.com/#!9/6983b9

2 个答案:

答案 0 :(得分:1)

  • 您可以在一组created_date上使用条件函数Count() If()进行费用交易的总数。
  • 类似地,您可以在created_dateSum()使用If()完成费用。

尝试以下操作:

SELECT 
  `created_date`, 
  SUM(IF (`type` = 2, `amount`, 0)) AS total_expense_amount, 
  COUNT(IF (`type` = 2, `id`, NULL)) AS expense_count  
FROM 
  `transaction` 
GROUP BY `created_date` 
ORDER BY `created_date` ASC 

答案 1 :(得分:0)

您只想要一个WHERE子句吗?

SELECT t.created_date, SUM(amount) as total_amount
FROM transaction t
WHERE type = 2
GROUP BY t.created_date
ORDER BY created_date ASC ;