[英]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.上面的查询输出 10 行。 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.我试图实现 SQL COUNT function 但由于它有一个 INNER JOIN,所以我在语法上苦苦挣扎。
If you are running MySQL 8.0, you can do a window count:如果您运行的是 MySQL 8.0,您可以进行 window 计数:
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)每个非聚合列都应该属于
group by
子句(这是一种很好的做法,也是大多数数据库的要求)
if you are not using Mysql 8.0 you can use Subquery:如果您不使用 Mysql 8.0,您可以使用子查询:
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:如果您使用的是 MYSQL 8.0,请使用 window function,如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.