I have a table myTable that looks like this:
+-------+-------+--------+------------+ | 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 | +-------+-------+--------+------------+
for a given date range, I need to show count of rows per date, per agent, and count(rows)-count(qualif = Q1) / count(rows)
To explain more, the way I do it on my PHP page is query first for:
SELECT date, Agent, count(*) as tot FROM myTable WHERE date between d1 and d2 group by date, agent
And when looping through the result for each agent and date, I query for:
SELECT count(*) as totQ1 FROM my table WHERE date='somedate' and agent='someagent' and qualif='Q1'
The expected result for a period between ‘2019-05-11’ AND ‘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 | +------------+--------+-----+-----------+
taking into consideration if tot=0;
Is there any way I can combine all of this into one query so I don’t have to query multiple times for each date and agent?
Advertisement
Answer
You could use conditional SUM()
, as in:
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