我有一个表myTable,看起来像这样:
+-------+-------+--------+------------+
| Id | Agent | Qualif | Date |
+-------+-------+--------+------------+
| 1 | A | Q1 | 2019-05-11 |
| 2 | B | Q2 | 2019-05-11 |
| 3 | C | Q1 | 2019-05-12 |
| 4 | A | Q1 | 2019-05-11 |
| 5 | A | Q2 | 2019-05-11 |
+-------+-------+--------+------------+
对于给定的日期范围,我需要显示每个日期,每个代理的行数以及count(rows)-count(qualif = Q1)/ count(rows)
为进一步说明,我在PHP页面上的操作方式首先是查询:
SELECT date, Agent, count(*) as tot
FROM myTable
WHERE date between d1 and d2
group by date, agent
当遍历每个座席和日期的结果时,我查询:
SELECT count(*) as totQ1 FROM my table WHERE date='somedate' and agent='someagent' and qualif='Q1'
“ 2019-05-11”至“ 2019-05-12”之间的预期结果
+------------+--------+-----+-----------+
| date | Agent | tot | division |
+------------+--------+-----+-----------+
| 2019-05-11 | A | 3 | 2/3 |
| 2019-05-11 | B | 1 | 1 |
| 2019-05-12 | C | 1 | 1 |
+------------+--------+-----+-----------+
考虑是否tot = 0;
有什么办法可以将所有这些组合到一个查询中,这样我就不必为每个日期和座席多次查询?
答案 0 :(得分:0)
您可以使用条件SUM()
,如下所示:
SELECT
date,
Agent,
count(*) as tot,
sum(case when Qualif = 'Q1' then 1 else 0 end) / count(*) as division
FROM myTable
WHERE date between d1 and d2
GROUP BY date, agent