使用mysql计算组计数,给定日期的总和

时间:2013-01-16 10:23:14

标签: mysql sql

我有一张存储发票数据的表格。付款后is_paid将被标记为1

因此,我要做的是获取给定日期的每个用户的所有未付发票(where is_paid =0),以及每个员工的待处理总金额以及该期间的待处理发票数

SELECT
              receivable.amount,
              receivable.admission,
receivable.grouped,
              receivable.month,
              emp.name
            FROM
              receivable JOIN students ON receivable.emp_id = emp.id
where receivable.is_paid='0' 
group by receivable.emp_id
ORDER BY CAST(receivable.grouped AS UNSIGNED ) , receivable.grouped

如何更改上述代码以计算给定期间的待处理发票数,每个用户的待处理金额总和以及该期间的分组总数(用户输入日期以便记录需要显示所有内容)在那之前,包括那个日期)

以下是报告结构

enter image description here

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

猜测month指的是本月的第一天 - 如果你能澄清这一点,我可以写一些更准确的东西。实质上,您需要使用SUM和COUNT聚合函数,并声明每个其他列作为GROUP BY子句的一部分返回:

SELECT
  receivable.emp_id,
  emp.name,
  receivable.grouped,
  receivable.month,
  SUM(receivable.amount) as totalAmount
  COUNT(*) as totalCount
FROM receivable 
JOIN emp ON receivable.emp_id = emp.id
WHERE receivable.is_paid='0'
  AND receivable.month = '2013-01-01'
GROUP BY receivable.emp_id, emp.name, receivable.grouped, receivable.month
ORDER BY CAST(receivable.grouped AS UNSIGNED ), receivable.grouped