简体   繁体   中英

Implementing Count Function In SQL Query With Inner Joins

I have a query which is the following:

 select person.ID, person.personName, round(avg(TIMESTAMPDIFF(DAY,orderDate,shippedDate)),2)) as 'Average' from orders inner join person person.personID= orders.personID where shippedDate is not null group by orders.personID;

The query above outputs 10 rows. I want to add a field which would count how how many rows there are in the query above in total.

I have tried to implement the SQL COUNT function but am struggling with the syntax as it has an INNER JOIN.

If you are running MySQL 8.0, you can do a window count:

select 
    person.ID, 
    person.personName, 
    round(avg(timestampdiff(day, o.orderDate, o.shippedDate)),2)) average,
    count(*) over() total_no_rows
from orders o
inner join person p on p.personID = o.personID 
where o.shippedDate is not null 
group by p.personID, o.personName

Note that I made a few fixes to your query:

  • table aliases make the query easier to read and write

  • it is a good practice to qualify all column names with the table they belong to - I made a few assumptions that you might need to review

  • every non-aggregated column should belong to the group by clause (this is a good practice, and a requirement in most databases)

if you are not using Mysql 8.0 you can use Subquery:

select COUNT(*) FROM (
  person.ID,
  person.personName, 
  round(avg(TIMESTAMPDIFF(DAY,orderDate,shippedDate)),2)) as 'Average' from 
  orders inner join person person.personID= orders.personID where shippedDate 
  is not null group by orders.personID
);

and if you are using MYSQL 8.0 use window function like below:

select 
    person.ID, 
    person.personName, 
    round(avg(timestampdiff(day, o.orderDate, o.shippedDate)),2)) average,
    count(*) over() total_no_rows
from orders o
inner join person p on p.personID = o.personID 
where o.shippedDate is not null 
group by p.personID, o.personName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM