从a 中选出计数?
我有一个表,看起来像这样:
mysql> describe tb_exifinfo;
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| filename | char(18) | NO | PRI | | |
| iso | mediumint | YES | | NULL | |
| aperture | decimal(3,1) | YES | | NULL | |
| exposuretime | tinytext | YES | | NULL | |
| focal_length | smallint | YES | | NULL | |
| lens | tinytext | YES | | NULL | |
| date | date | NO | PRI | NULL | |
| time | time | NO | PRI | NULL | |
| model | tinytext | YES | | NULL | |
| flash | tinyint(1) | YES | | NULL | |
| fìle_size | decimal(3,1) | YES | | NULL | |
| orientation | tinytext | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
12 rows in set (0.00 sec)
with a as (
select model as model, lens, count(*) N
from tb_exifinfo
group by model,lens
order by model )
, b as (
select model, max(N) as maxN
from a
group by model)
select a.model, a.lens, a.N
from a join b on a.model=b.model and a.N=b.maxN;
这会给出我的输出:
+------------------------+------------------------------+------+
| model | lens | N |
+------------------------+------------------------------+------+
| Canon EOS 350D DIGITAL | Sigma 18-50f/2.8 EX DC HSM | 3959 |
| Canon EOS 600D | Canon EF 24-70mm f/2.8L USM | 2480 |
| Canon EOS 6D Mark II | Canon EF 16-35mm f/4L IS USM | 1017 |
| Canon EOS R6 Mark III | Sigma 50mm f/1.4 DG HSM | A | 45 |
+------------------------+------------------------------+------+
4 rows in set (0.02 sec)
然而,那不是我想要的,我想知道每个相机机身上使用了多少支镜头。我已经四处查看并尝试了各种查询,但仍没搞懂这一点。能不能请人帮忙?
解决方案
你可以用下面的查询,得到每个相机型号使用的不同镜头数量:
select model, count(distinct lens) as number_of_different_lenses
from tb_exifinfo
group by model;
在请求的注释里,你说你用下面这个查询解决了问题,尽管:
with
a as
(
select model, count(distinct lens) N
from tb_exifinfo
group by model
order by model
),
b as
(
select model, max(N) as maxN
from a
group by model
)
select a.model, a.N
from a
join b on a.model=b.model and a.N=b.maxN;
这个查询太复杂了。
- 在
a中,你得到每个模型的镜头数量,也就是每个模型一行。这里的ORDER BY子句是多余的。 - 然后,在
b中,你说“从这些行(每个模型一行)再给我一行每个模型”。这没有意义。你得到的是相同的行,只是你之前称为N的,现在改为了maxN。相同的行、相同的数据,只是列名换了,因为一个值集合的最大值当然就是它本身。 - 现在你把
a和b连接起来,当然又得到相同的数据,只是多出重复的列。
因此,用我上面提到的那个简单查询来替换你的查询。在末尾再加上一个 ORDER BY 子句,以按你希望的顺序得到这些行。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。